Image Binarization

RGB to Binary image conversion in Javascript

Image binarization converts a grayscale image to binary image (only two level pixel values). A grayscale image pixels have 0 upto 256 gray levels. Binarization is used very frequently in many image processing applications like image segmentation, OCR techniques to read the text content in an image.

Image binarization can be categorised into mainly two categories:

  1. Global Binarization
  2. Local Binarization

Global thresholding can be done by choosing a fixed global threshold value to classify the graylebel pixels in to two levels (binary pixel values). Threshold value selection is the key point in image binarization process so it should be carefully chosen to get correct binary image. Threshold value can be either selected manually as a fixed value based on image pixels analysis or it can be selected automatically based on the shape of gray level image histogram.For autothresholding OTSU's threshlding algorithm is used.

In this tutorial we will implement the fixel threshold value based binarization method in Javascript(Frontend side). Generally we do heavy image processing operations on server for high performance reason but it increases the load on the server. So doing low level image preocessing operation in front-end will reduce the load on server and it will also help in performing real time image processing operations without server dependency.

Tip!

The Basic idea for fixed binarization method can be formulated mathematically as below:

The HTML canvas element is used to draw graphics in JavaScript. So we will use canvas to load the input image. To draw an image using HTML5 Canvas, we can use the drawImage() method which requires an image object and a destination point.

      
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var imageObj = new Image();
        var imgWidth,imgHeight;
        imageObj.onload = function() {
          canvas.width = imgWidth = img.width;
          canvas.height = imgHeight = img.height;
          context.drawImage(imageObj, imgWidth, imgHeight);
          imagedata = context.getImageData(0,0,imgWidth,imgHeight);
          rgbtobinary(imagedata.data);
        };

        imageObj.src = 'rgb-img.jpg'; // input image
      
    

Now we have successfully drawn rgb image onto canvas and read the image data.

Next we need to define a new funtion to convert rgb image pixels to gray scale level-

      
        function rgb2gray(pix,offset){
          return ( 0.34*pix[offset] + 0.5*pix[offset+1] + 0.16*pix[offset+2] );
        }
      
    
      
        function rgbtobinary(pix){
          var newpix = pix;
          var gray;
          var len = pix.length;
          var threshold = 128; 
          for(var i=0;i< len;i+=4){
            gray = rgb2gray(pix,i); // rgb to gray image conversion
            if(gray>threshold){
              newpix[i] = 255;
              newpix[i+1] = 255;
              newpix[i+2] = 255;
            }
            else{
              newpix[i] = 0;
              newpix[i+1] = 0;
              newpix[i+2] = 0;
            }
            newpix[i+3] = pix[i+3];
          }
        }

        drawImage(newpix);
      
    

Above we converted rgb pixels to gray which were then converted binary level values [0,255] by comapring with fixed threshold value.

Next we need to redraw the newpix data onto canvas to display the binary image.

      
        function drawImage(newpix){
          var newvancas = document.createElement('canvas');
          newcanvas.width = imgwidth;
          newcanvas.height = imgHeight;
          var context = newcanvas.getContext('2d');
          var newimg = context.createImageData(imgWidth,imgHeight);
          newimg.data.set(newpix);
          context.putImageData(newimg,0,0);
          var targetImg = new Image();
          targetimg.src = newcanvas.toDataURL("image/png");
          $target = $("#binimg");
          $target.html(targetimg);
        }
      
    

Final code-

      
        var imageObj = new Image();
        imageObj.src = 'rgb-img.jpg'; // input image
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var imgWidth,imgHeight;
        imageObj.onload = function() {
          canvas.width = imgWidth = img.width;
          canvas.height = imgHeight = img.height;
          context.drawImage(imageObj, imgWidth, imgHeight);
          imagedata = context.getImageData(0,0,imgWidth,imgHeight);
          rgbtobinary(imagedata.data);
        };

        function rgb2gray(pix,offset){
            return ( 0.34*pix[offset] + 0.5*pix[offset+1] + 0.16*pix[offset+2] );
        }

        function rgbtobinary(pix){
            var newpix = pix;
            var gray;
            var len = pix.length;
            var threshold = 128; 
            for(var i=0;i < len;i+=4){
              gray = rgb2gray(pix,i); // rgb to gray image conversion
              if(gray>threshold){
                newpix[i] = 255;
                newpix[i+1] = 255;
                newpix[i+2] = 255;
              }
              else{
                newpix[i] = 0;
                newpix[i+1] = 0;
                newpix[i+2] = 0;
              }
              newpix[i+3] = pix[i+3];
            }
            drawImage(newpix);
        }

        function drawImage(newpix){
            var newvancas = document.createElement('canvas');
            newcanvas.width = imgwidth;
            newcanvas.height = imgHeight;
            var context = newcanvas.getContext('2d');
            var newimg = context.createImageData(imgWidth,imgHeight);
            newimg.data.set(newpix);
            context.putImageData(newimg,0,0);
            var targetImg = new Image();
            targetimg.src = newcanvas.toDataURL("image/png");
            $target = $("#binimg");
            $target.html(targetimg);
        }

      
    

Recently Added Tutorial