gpt4 book ai didi

javascript - Canvas 颜色匹配范围

转载 作者:行者123 更新时间:2023-11-29 21:44:50 25 4
gpt4 key购买 nike

我当前的代码在 Canvas 上扫描一种颜色,然后将其从 Canvas 上移除并移动到下一个像素。我想要实现的是颜色搜索的强度。所以我们也找到相似的颜色,而不仅仅是一种 RGBA 颜色。

这可能吗,这是我的一种颜色的工作代码。

当前代码

    //1-225
threshold = 100;

//Get Canvas Element Data
imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height);
data = imageData.data;

//RGB
color = [120, 82, 31, 1];

for (var i = 0, n = data.length; i <n; i += 4) {
if(data[i] === color[0] && data[i+1] === color[1] && data[i+2] === color[2]){
data[i+3] = 1;
}
}

context.putImageData(imageData, 0, 0);

最佳答案

免责声明

这个答案是基于 OP 的代码,可能不是最好的方法。


要检查实际像素是否在您定义的阈值范围内,您可以使用类似 if 的语句:
if(data[i]>=color[0]-threshold/2 && data[i]<=color[0]+threshold/2 && data[i+1]>=color[1]-threshold/2 && data[i+1]<=color[1]+threshold/2 && data[i+2]>=color[2]-threshold/2 && data[i+2]<=color[2]+threshold/2

或者,为了更清楚,你可以创建一个函数来检查这个分支:

function isBetween(value, i){
return (value>=color[i]-threshold/2 && value<=color[i]+threshold/2)
}

然后像这样使用它:

if( isBetween(data[i],i%4) && isBetween(data[i+1],i%4+1) && isBetween(data[i+2],i%4+2) ){ doSomething() }

一个完整的例子:

var canvasEl = document.createElement('canvas');
var context = canvasEl.getContext('2d');
document.body.appendChild(canvasEl);
var imageData;

var img = new Image();
img.crossOrigin='anonymous';
img.onload = function(){
canvasEl.height = 250;
canvasEl.width = 400;
context.drawImage(this, 0,0,canvasEl.width,canvasEl.height);
imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height);
}
// image by Levanne (https://www.flickr.com/photos/lfphotos/14282259549/) CC BY-SA 2.0
img.src = 'https://dl.dropboxusercontent.com/s/te5g7s1lh122quy/1024px-Levanne_%2814282259549%29.jpg?dl=0';

var input = document.querySelector('input');
input.addEventListener('change', colorIntesityThreshold, false);


function colorIntesityThreshold(){
var threshold = this.value;
var data = imageData.data;
var newData = new Uint8ClampedArray(data);
//RGB
var color = [50, 100, 255, 1];

function isBetween(val, i){
return (val>=(color[i]-threshold/2) && val<=(color[i]+threshold/2))
}

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

if( isBetween(data[i],i%4) && isBetween(data[i+1],i%4+1) && isBetween(data[i+2],i%4+2) ){

newData[i+3]=0;
}
}
var newImg = new ImageData(newData, canvasEl.width,canvasEl.height);
context.putImageData(newImg, 0, 0);
}
<input type="range" min="0" max="255" value="0"/>

关于javascript - Canvas 颜色匹配范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31584866/

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