How to Implement Binarization using HTML5 and JavaScript?
How to implement binarization using HTML5 and Javascript?¶
Introduction
Sometimes, we need to transform color images to monochrome image. There is one way that it is very simple to help you to do. You can download source code and binary files. Even I refer to OpenCV book, but I think it is so easy. I decide to implement it by myself.
Equipment
Operation System: Microsoft Windows 7 Professional (64 bit)
Development Utility: HTML5 and Javascript
Usage
<!DOCTYPE html> <html> <head> <script type="text/javascript"> function imageLoaded(ev) { element = document.getElementById("cancan"); c = element.getContext("2d"); // The image, assumed to be 512x512 im = ev.target; // Read the width and height of the canvas width = element.width; height = element.height; // Stamp the image on the left of the canvas. c.drawImage(im, 0, 0); // Get all canvas pixel data imageData = c.getImageData(0, 0, width, height); // The width index is output position. w2 = width / 2; // Run through the image. // The height of the image. for (y = 0; y < height; y++) { // *4 for 4 ints per pixel. // This is an input index. inpos = y * width * 4; // This is an output index. outpos = inpos + w2 * 4 // The width of the image. for (x = 0; x < w2; x++) { // Get the pixel of the red channel. r = imageData.data[inpos++] // Get the pixel of the green channel. g = imageData.data[inpos++] // Get the pixel of the blue channel. b = imageData.data[inpos++] // Get the pixel of the alpha channel. a = imageData.data[inpos++] // Transform RGB color space to gray scale. gray = (0.299 * r + 0.587 * g + 0.114 * b) // This is our threshold. You can change it. if ( gray > 120 ) { // Set the pixel is white. imageData.data[outpos++] = 255; imageData.data[outpos++] = 255; imageData.data[outpos++] = 255; imageData.data[outpos++] = a; } else { // Set the pixel is black. imageData.data[outpos++] = 0; imageData.data[outpos++] = 0; imageData.data[outpos++] = 0; imageData.data[outpos++] = a; } } // The closing "The width of the image". } // The closing "The height of the image". // Put pixel data on canvas. c.putImageData(imageData, 0, 0); } // Establish an image object. im = new Image(); // Load the javascript function. im.onload = imageLoaded; // Code assumes this image is 512x512. im.src = "B_01.jpg"; </script> </head> <body> <!-- Create a canvas --> <canvas id="cancan" width="1024", height="512">Canvas</canvas> </body> </html>
Download source code and binary files:
https://drive.google.com/file/d/0BzHb_OyLyVZlSU1pcXM1ZFh5ZnM/view?usp=sharing
Exception
None.
Reference
[1] Gary Bradski and Adrian Kaehler, “Learning OpenCV: Computer Vision with the OpenCV Library,” O’REILLY, September 2008, ISBN:978-0-596-51613-0
Acknowledge
Thank you (HTML5, Javascript, Lenna Sjööblom) very much for this great development utility and beautiful photo.