Converting An HTML5 Canvas To Black And White

As part of the OCR in my Draw Something Solver, I needed to turn animage into a two tone black and white image. This is really simple to do. Firstly you need to turn the image to grayscale, then you need to turn all pixels with a value over a certain threshold to 255 for the red, green and blue values, or to 0 if under the threshold.

I’ve already covered Grayscaling an HTML 5 Canvas so I will assume this has already taken place and you have the ImageData from an HTML 5 Canvas in an object called imageData.

To turn this to a black and white image we can use the following code…

for (var i = 0; i < imageData.data.length; i+=4) {
  imageData.data[i] = imageData.data[i+1] = imageData.data[i+2] = imageData.data[i] > threshold ? 255 : 0;
}

You just need to change the value of the threshold variable to adjust the sensitivity of the conversion.

Taking the previous red channel image conversion…

grayscale image

Setting the threshold to 200, the converted black and white image looks like this…

black and white image