gpt4 book ai didi

javascript - canvas getImageData 方法是否依赖于机器/浏览器?

转载 作者:数据小太阳 更新时间:2023-10-29 04:42:20 24 4
gpt4 key购买 nike

一位客户需要有关提取产品图片主色的程序的帮助。

我能够用 Javascript 快速实现它;下面的算法仅对图像上 3x3 网格的中心方 block 进行采样,以快速估计图像中的 T 恤颜色。

var image = new Image();
image.onload = function() {
try {
// get dominant color by sampling the central square of a 3x3 grid on image
var dominantColor = getDominantColor();

// output color
$("#output").html(dominantColor);
}
catch(e) {
$("#output").html(e);
}
};
image.src = "sample_image.jpg";

function getDominantColor() {

// Copy image to canvas
var canvas = $("<canvas/>")[0];
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);

// get pixels from the central square of a 3x3 grid
var imageData = canvas.getContext("2d").getImageData(canvas.width/3, canvas.height/3, canvas.width/3, canvas.height/3).data;

var colorOccurrences = {};
var dominantColor = "";
var dominantColorOccurrence = 0;

for(var i = 0; i < imageData.length; i += 4) {
var red = imageData[i];
var green = imageData[i+1];
var blue = imageData[i+2];
//var alpha = imageData[i+3]; // not required for this task

var color = RGBtoHEX({"red": red, "green": green, "blue": blue});

if(colorOccurrences[color] == undefined) {
colorOccurrences[color] = 1;
}
else {
colorOccurrences[color] ++;

if(colorOccurrences[color] > dominantColorOccurrence) {
dominantColorOccurrence = colorOccurrences[color];
dominantColor = color;
}
}
}

return dominantColor;
}

function RGBtoHEX(rgb) {
var hexChars = "0123456789ABCDEF";
return "#"
+ (hexChars[~~(rgb.red/16)] + hexChars[rgb.red%16])
+ (hexChars[~~(rgb.green/16)] + hexChars[rgb.green%16])
+ (hexChars[~~(rgb.blue/16)] + hexChars[rgb.blue%16]);
}

有问题的图像是 this(下面的预览)。

Sample product

但是,在上述代码中处理此图像的结果因机器/浏览器而异:#FF635E 是我在运行 Windows7 和使用 Firefox 32。我运行 Mac 的客户端在 Safari 上得到的结果是 #FF474B,在 Firefox 33 上得到的结果是 #FF474C .

虽然结果很接近,但为什么理想情况下它们并不完全相同? getImageData 是否确实因本地设置而异,或者JPG 数据在不同机器上的解释不同吗?

编辑:这张图片不是一次性的。在客户要求处理的一系列图像中发现了这种颜色变化。我和我的客户对同一组图像获得了不同的结果。

最佳答案

是的。 canvas fingerprinting 利用了这一事实:

The same HTML5 Canvas element can produce exceptional pixels on a different web browsers, depending on the system on which it was executed.

This happens for several reasons: at the image format level — web browsers uses different image processing engines, export options, compression level, final images may got different hashes even if they are pixel-perfect; at the pixmap level — operating systems use different algorithms and settings for anti-aliasing and sub-pixel rendering. We don't know all the reasons, but we have already collected more than a thousand unique signatures.

关于javascript - canvas getImageData 方法是否依赖于机器/浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26615580/

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