JS - 在图像

时间:2017-11-21 23:10:07

标签: javascript

我有一堆像这样的图像: http://i.imgur.com/kW8UaA4.png

我需要找到黑暗方块中间的x,y。 我目前有以下代码: https://jsfiddle.net/brampower/tw08fdhf/

function rgbToHsl(r, g, b) {
    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b),
        min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;

    if (max == min) {
        h = s = 0; // achromatic
    } else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch (max) {
            case r:
                h = (g - b) / d + (g < b ? 6 : 0);
                break;
            case g:
                h = (b - r) / d + 2;
                break;
            case b:
                h = (r - g) / d + 4;
                break;
        }
        h /= 6;
    }

    return ({
        h: h,
        s: s,
        l: l,
    });
}

function solve_darkest(url, callback) {
    var image = new Image();
  image.crossOrigin = "Anonymous";
    image.src = url;

    image.onload = function(){
        var canvas = document.createElement('canvas');

    var WIDTH = image.width;
    var HEIGHT = image.height;

        canvas.width  = WIDTH;
        canvas.height = HEIGHT;

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

    document.body.appendChild(canvas);

        var imgData = context.getImageData(0, 0, WIDTH, HEIGHT);

        var pixel = 0;
        var darkest_pixel_lightness = 100;
        var darkest_pixel_location = 0;
        for (var i = 0; i < imgData.data.length; i += 4, pixel++) {
            red = imgData.data[i + 0];
            green = imgData.data[i + 1];
            blue = imgData.data[i + 2];
            alpha = imgData.data[i + 3];

      if (alpha < 230) {
        continue;
      }
      console.log(Math.floor(pixel / WIDTH) + " ", i % WIDTH);


            var hsl = rgbToHsl(red, green, blue);
            var lightness = hsl.l;

            if (lightness < darkest_pixel_lightness) {
                darkest_pixel_lightness = lightness;
                darkest_pixel_location = pixel;
            }
        }

        var y = Math.floor(darkest_pixel_location / WIDTH);
        var x = darkest_pixel_location % WIDTH;

        callback(x,y);
    };
}

image_url = 'http://i.imgur.com/kW8UaA4.png';
solve_darkest(image_url, function(x, y) {
    setTimeout(function() {
        alert('x: '+x+' y: '+y);
    }, 100);
});

但它没有给我我期待的结果。它遍历所有像素,然后返回最暗像素的x和y。然而,看起来最暗的像素不存在于黑暗的方形区域中。 我该怎么做才能让它返回深色方块中间的x,y?

0 个答案:

没有答案