完成算法以从图片生成颜色优势直方图(在JavaScript中)

时间:2012-12-04 13:03:43

标签: javascript image colors palette

我需要找出图像的N种主色。 我写了一个灵感来自于此的函数:http://bubble.ro/How_to_create_the_histogram_of_an_image_using_PHP.html

图片是在与图片具有相同表面的隐藏画布内绘制的。

这是我的代码:

lwf.image.getDominantColors = function(args) {

    // args.imageData is the ImageData object got from the canvas 2d context.
    // canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height)

    if(!args.imageData) alert('lwf::image::getDominantColors() : no ImageData provided.');

    // args.sampling defines the percentage of pixels to be tested (0.01 for example).

    var sampling = undefined != args.sampling && 0 > args.sampling && args.sampling <= 1
      ? args.sampling
      : lwf.image.DFLT_PX_SAMPLING_RATIO; // Default value

    var w = args.imageData.width,
        h = args.imageData.height,
        total = w * h,
        mat = args.imageData.data;

    // Interval allows me to skip pixels on X and Y axis to make the computation faster.
    // The top-left pixel of each interval * interval square is tested.

    var interval = Math.round(Math.sqrt(1 / sampling));

    var histogram = new Array();

    var x = 0, y = 0, // Coordinates of the tested pixel.
        i = 0, j = 0; // Use to get the number of tested pixels.

    for(i = 0, x = 0; x < w; ++i, x += interval) {

        for(j = 0, y = 0; y < h; ++j, y += interval) {

            var start = (y * w + x) << 2;

            var r = mat[start    ],
                g = mat[start + 1],
                b = mat[start + 2];

            var value = Math.round((r + g + b) / 3);

            // TODO
        }
    }

    var tested = i * j;

    // TODO

    return histogram;

}; // lwf::image::getDominantColors()

我不知道如何完成此操作,以便它返回一个等效的PHP数组,指示找到的foreach颜色,表示其存在的值。

另一个问题:以下表达式代表什么?

var value = Math.round((r + g + b) / 3);

这很奇怪,因为如果我们有r = 200,g = 100,b = 100和r = 100,g = 100,b = 200,两者将具有相同的值但是对于两种不同的颜色。在我找到的教程中没有对此进行解释。

有没有人有想法?在此先感谢:)

0 个答案:

没有答案
相关问题