Image brightness detection in client side script

My answer reuses most of the code in @lostsource's answer but it uses a different method to attempt to distinguish between dark and light images.

First we need to (briefly) analyze what is the result of the average value of the sum of the RGB channels. For humans, it is meaningless. Is pink brighter than green? I.e., why would you want (0, 255, 0) to give a lower brightness value than (255, 0, 255)? Also, is a mid gray (128, 128, 128) bright just like a mid green (128, 255, 0)? To take this into consideration, I only deal with the color brightness of the channel as is done in the HSV color space. This is simply the maximum value of a given RGB triplet.

The rest is heuristics. Let max_rgb = max(RGB_i) for some point i. If max_rgb is lower than 128 (assuming a 8bpp image), then we found a new point i that is dark, otherwise it is light. Doing this for every point i, we get A points that are light and B points that are dark. If (A - B)/(A + B) >= 0 then we say the image is light. Note that if every point is dark, then you get a value of -1, conversely if every point is light you get +1. The previous formula can be tweaked so you can accept images barely dark. In the code I named the variable as fuzzy, but it does no justice to the fuzzy field in Image Processing. So, we say the image is light if (A - B)/(A + B) + fuzzy >= 0.

The code is at http://jsfiddle.net/s7Wx2/328/, it is very straightforward, don't let my notations scare you.


This function will convert each color to gray scale and return average of all pixels, so final value will be between 0 (darkest) and 255 (brightest)

function getImageLightness(imageSrc,callback) {
    var img = document.createElement("img");
    img.src = imageSrc;
    img.style.display = "none";
    document.body.appendChild(img);

    var colorSum = 0;

    img.onload = function() {
        // create canvas
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this,0,0);

        var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
        var data = imageData.data;
        var r,g,b,avg;

        for(var x = 0, len = data.length; x < len; x+=4) {
            r = data[x];
            g = data[x+1];
            b = data[x+2];

            avg = Math.floor((r+g+b)/3);
            colorSum += avg;
        }

        var brightness = Math.floor(colorSum / (this.width*this.height));
        callback(brightness);
    }
}

Usage:

getImageLightness("image.jpg",function(brightness){
    console.log(brightness);
});

JSFiddle:

http://jsfiddle.net/s7Wx2/


A script called Background Check can detect the darkness/lightness in an image. It uses JavaScript to do so.

Here is a link to it:

http://www.kennethcachia.com/background-check/

I hope that helps anyone wanting to make a slider with this type of detection within it.