【发布时间】:2021-02-25 03:06:22
【问题描述】:
对于创建一个函数以将单个 RGB 值与 RGB 值数组进行比较并确定它是否在阈值范围内,我将不胜感激。这是使用 HTML5 canvas 元素在 vanilla javascript 中完成的。
我的第一次尝试:
var colorArray = [ //rgb values to search through
[212, 35, 96],
[200, 200, 150],
[100, 100, 75]
];
var threshold = 15; //the threshold
//Given a canvas with an image drawn on it
var pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height); // get the canvas pixel data
for(var row = 0; row < canvas.height; row++){ //stepping through the pixels
for (var col = 0, index = 0, colorTotal = 0; col < canvas.width; col++){
index = (col + (row * canvas.width)) * 4;
colorTotal = pixelData.data[index] + pixelData.data[index + 1] + pixelData.data[index + 2]; //add the rgb values of the current pixel
for(var i = 0, pixelColorTotal = 0, result = 0; i < colorArray.length; i++){ //stepping through the colorArray
pixelColorTotal = colorArray[i] [0] + colorArray[i] [1] + colorArray[i] [2]; //add the rgb values of the current array element
result = Math.abs(colorTotal - pixelColorTotal); //find the difference between the color totals
if(result < threshold){
//..do something we've breached the threshold
}
}
}
}
这效果不太好,因为例如:[255, 0, 50] 和 [50, 255, 0] 甚至不接近相同的颜色,但它们会超出阈值。
我的第二次尝试:
var colorArray = [ //rgb values to search through
[212, 35, 96],
[200, 200, 150],
[100, 100, 75]
];
var threshold = 15; //the threshold
//Given a canvas with an image drawn on it
var pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height); // get the canvas pixel data
for(var row = 0; row < canvas.height; row++){ //stepping through the pixels
for (var col = 0, index = 0; col < canvas.width; col++){
index = (col + (row * canvas.width)) * 4;
for(var i = 0, result = 0; i < colorArray.length; i++){ //stepping through the colorArray
result = Math.abs(pixelData.data[index] - colorArray[i] [0]); //load red difference
if(result >= threshold){ //check the red channel to see if it exceeds threshold
result = Math.abs(pixelData.data[index + 1] - colorArray[i] [1]); //load green difference
if(result >= threshold){ //check the green channel to see if it exceeds threshold
result = Math.abs(pixelData.data[index + 2] - colorArray[i] [2]); //load blue difference
if(result >= threshold){ //check the green channel to see if it exceeds threshold
//do something we have passed all the threshold checks
}
}
}
}
}
}
这样更好,但效率很低。
有没有更好的想法?感谢阅读。
【问题讨论】:
标签: javascript arrays canvas threshold