Best RGB combination to convert image into Black and White "threshold"

Viewed 4318

I am required to build a simple application that converts a color image or a grayscale image into a black and white one, I was thinking looping through each pixel and checking the RGB values and if all of them are less than an specific value (lets say 20) redraw the pixel to black and if it is greater than that value, redraw the pixel to white. Something like this.

function blackWhite(context, canvas) {
    var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
        var pixels  = imgData.data;
        for (var i = 0, n = pixels.length; i < n; i += 4) {
        if (pixels[i] <= 20 || pixels[i+1] <= 20 || pixels[i+2] <= 20){ 
              pixels[i  ] = 0;        // red
           pixels[i+1] = 0;        // green
           pixels[i+2] = 0;        // blue
        }else{
              pixels[i  ] = 255;        // red
           pixels[i+1] = 255;        // green
           pixels[i+2] = 255;        // blue
        }
    }
    //redraw the image in black & white
    context.putImageData(imgData, 0, 0);
  }

The big question is, what is the correct combination of Red, green and blue to define a pixel to be black, this taking into account that colors are perceived different by the human eye, as an example for our eyes it is more important the green color than the red and the blue, I’ve tried experimentally some values, but I don’t get close to a black and with image like the one you could get by digitalizing a sheet in an scanner as black and white.

Of course if there is a much faster way to do this, I will totally appreciate it.

3 Answers
Related