![](/img/trans.png)
[英]Display image from array of pixels on Canvas with OpenCV and Javascript
[英]Extract pixels from canvas-Array
我目前正在从事一个项目,为此我需要处理画布的像素。 我确实通过使用canvascontext.getImageData(0,0,width,height).data()来提取像素。 这段代码运行良好,并返回一个像素数组。 在此阵列内,像素的位置如下:[r1,g1,b1,a1,r2,g2,b2,a2 ...]。 现在,我已经在Java中使用了类似的数组,但是这里返回的像素是这样的:[r1,r2,g1,g2,b1,b2,a1,a2]这使得使用遮罩获取值成为可能。 。 由于JS中的代码不同,因此我使用以下函数从数组中提取值并在编辑后进行设置:
ImageClass.prototype.getRed = function(temp){
return imageData.pixels[temp];
}
ImageClass.prototype.setRed = function(r, temp){
imageData.pixels[temp] = r;
}
ImageClass.prototype.getGreen = function(temp){
return imageData.pixels[Number(temp)+1];
}
ImageClass.prototype.setGreen = function(g, temp){
imageData.pixels[Number(temp)+1] = g;
}
ImageClass.prototype.getBlue = function(temp){
return imageData.pixels[Number(temp)+2];
}
ImageClass.prototype.setBlue = function(b, temp){
imageData.pixels[Number(temp)+2] = b;
}
ImageClass.prototype.getAlpha = function(temp){
return imageData.pixels[Number(temp)+3];
}
ImageClass.prototype.setAlpha = function(a, temp){
imageData.pixels[Number(temp)+3] = a;
}
temp是一个整数值,代表一个索引。 现在我的问题是:虽然以下功能(红色)有效,但下一个功能(绿色)无效。 我不知道为什么以及如何开始调试。
ImageClass.prototype.red = function(){
this.getPixels();
for (index = 0; index < imageData.pixelsLength; index += 4) {
var g = this.getGreen(index);
var b = this.getBlue(index);
g = 0;
b = 0;
this.setGreen(g, index);
this.setBlue(b, index);
}
this.draw();
}
ImageClass.prototype.green = function(){
this.getPixels();
for (index = 0; index < imageData.pixelsLength; index += 4) {
var r = this.getRed(index);
var b = this.getBlue(index);
r = 0;
b = 0;
this.setRed(r, index);
this.setBlue(b, index);
}
this.draw();
}
getPixels()函数仅使像素数组全局可用(在命名空间中)。 绘图功能确实可以如其名称所说的那样工作。
如果有人知道从数组中提取像素的简便方法,以便我可以访问所有红色,所有绿色等。我欢迎您提出建议。
提前致谢。
您可以删除对getGreen和getBlue的调用,因为无论如何它们都将覆盖它们。
ImageClass.prototype.red = function(){
this.getPixels();
for (index = 0; index < imageData.pixelsLength; index += 4) {
var g = 0, b = 0;
this.setGreen(g, index);
this.setBlue(b, index);
}
this.draw();
}
ImageClass.prototype.getRed
等。 如果您想要一个非常简单的方法,则可以执行以下操作:
offsets {r: 0, g: 1, b: 2, a: 3}
ImageClass.prototype.red = function(){
this.getPixels();
for (index = 0; index < imageData.pixelsLength; index += 4) {
imageData.pixels[index+offsets.g] = 0;
imageData.pixels[index+offsets.b] = 0;
}
this.draw();
}
您可以通过生成这些函数来避免重复代码。
offsets {r: 0, g: 1, b: 2, a: 3}
function MakeColorFunction(omit1, omit2){
return (function(){
this.getPixels();
for (index = 0; index < imageData.pixelsLength; index += 4) {
imageData.pixels[index+offsets[omit1]] = 0;
imageData.pixels[index+offsets[omit2]] = 0;
}
this.draw();
});
}
ImageClass.prototype.red = MakeColorFunction("g", "b");
ImageClass.prototype.green = MakeColorFunction("b", "r");
ImageClass.prototype.blue = MakeColorFunction("r", "g");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.