编程语言
首页 > 编程语言> > javascript – 如何在浏览器中进行对比度拉伸/规范化?

javascript – 如何在浏览器中进行对比度拉伸/规范化?

作者:互联网

我在网页上有jpegs.我想在没有浏览器插件的情况下对这些图像执行客户端均衡(对比度拉伸).我也接受直方图均衡的解决方案.

我目前使用两个CSS过滤器组合的差近似值(-webkit-filter:contrast()brightness()).

我希望能够用像processing.js或pixastic这样的东西来完成这个任务.

解决方法:

我不知道包含有效直方图均衡方法的库,而不会引入太多开销.但是,您可以非常快速地将自己的实现混为一谈.

您可以从这个非常优化的直方图均衡算法开始,该算法针对基于反投影从js-objectdetect获取的8位单通道图像:

/**
* Equalizes the histogram of an unsigned 1-channel image with values
* in range [0, 255]. Corresponds to the equalizeHist OpenCV function.
*
* @param {Array} src 1-channel source image
* @param {Array} [dst] 1-channel destination image. If omitted, the
* result is written to src (faster)
* @return {Array} Destination image
*/
equalizeHistogram = function(src, dst) {
    var srcLength = src.length;
    if (!dst) { dst = src; }

    // Compute histogram and histogram sum:
    var hist = new Float32Array(256);
    var sum = 0;
    for (var i = 0; i < srcLength; ++i) {
        ++hist[~~src[i]];
        ++sum;
    }

    // Compute integral histogram:
    var prev = hist[0];
    for (var i = 1; i < 256; ++i) {
        prev = hist[i] += prev;
    }

    // Equalize image:
    var norm = 255 / sum;
    for (var i = 0; i < srcLength; ++i) {
        dst[i] = hist[~~src[i]] * norm;
    }
    return dst;
}

您可以将此方法独立应用于RGB图像的各个通道,但这会产生不希望的结果. Wikipedia描述了一种更好的方法:

“However, if the image is first converted to another color space, Lab
color space, or HSL/HSV color space in particular, then the algorithm
can be applied to the luminance or value channel without resulting in
changes to the hue and saturation of the image.” (07001)

然后,您需要一个图像和一个canvas元素:

context = canvas.getContext("2d");
context.drawImage(image, 0, 0, canvas.width, canvas.height);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);

convertRGBAToHSL(imageData.data, hsl);
equalizeHistogram(hsl[2], hsl[2]);
convertHSLToRGBA(hsl, rgba);

如何执行RGBA< - > Javascript中的HSL对话在here中描述.

请记住,使用引用的转换方法,8位RGB图像有511种可能的亮度值.您的直方图应该是511而不是256个值的数组.您还必须确保亮度值在正确的范围内,可能乘以510或修改转换方法:

// r, g, b are in [0..255]
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var luminance = max + min;

标签:javascript,css,image-processing,histogram,contrast
来源: https://codeday.me/bug/20190620/1248227.html