gpt4 book ai didi

javascript - 了解 JavaScript 灰度算法的工作原理(不使用 jQuery)

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:17 24 4
gpt4 key购买 nike

今天在找一个将彩色图像转成灰度的算法,结果没找多久就找到了下面这篇文章

3 Ways to Turn Web Images to Grayscale

本文包含以下代码片段

var imgObj = document.getElementById('js-image');

function gray(imgObj) {
var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');

var imgW = imgObj.width;
var imgH = imgObj.height;
canvas.width = imgW;
canvas.height = imgH;

canvasContext.drawImage(imgObj, 0, 0);
var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

for (var y = 0; y < imgPixels.height; y++) {
for (var x = 0; x < imgPixels.width; x++) {
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}

imgObj.src = gray(imgObj);

也在这篇文章中http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html在评论中建议替换:

for (var y = 0; y < imgPixels.height; y++) {
for (var x = 0; x < imgPixels.width; x++) {
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}

与:

for (var i = 0; i < imgPixels.data.length; i = i + 4) {
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}

JSFiddle 上的演示 https://jsfiddle.net/n6q9a2c9/

而且我对这个算法的工作原理的理解有一些问题。

在这段代码中

for (var i = 0; i < imgPixels.data.length; i = i + 4) {
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}

我明白 var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2])/3 是公式 ( R + G + B)/3 下面是让我困惑的部分

for (var i = 0; i < imgPixels.data.length; i = i + 4) {

为什么这里我们递增 4?

如果能回答这个算法是如何工作的,我将不胜感激。

最佳答案

Canvas 数据以 RGBA(红色、绿色、蓝色和称为“alpha”的透明度值)交错格式提供给您。每个 channel 每个像素需要一个字节,而您有四个 channel ,因此每个像素有四个值。由于 channel 是交错的,因此您递增 4 以步进像素。

引用资料:

关于javascript - 了解 JavaScript 灰度算法的工作原理(不使用 jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39338608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com