Converting an image to grayscale in html5 canvas.

Understanding grayscale bitmap(digital) images:

Every pixel of a color(RGBA) image has three color channels and an alpha(transparency) channel. The value of each channel ranges from 0 to 255. So, a pixel may contain a value of 100 for red, 90 for green, 60 for blue, and 255 for alpha. If a pixel contains same values for all the color(RGB) channels, it will look gray.

example gray color shades

 

There is no unique formula to convert a color(RGB) image to grayscale because gray has multiple shades. In this page you will see two ways(formulae) to convert images to grayscale.

 

Learn about the basics of loading an image in canvas and manipulating its pixels.

In the tutorial above, see the part which shows how to access and manipulate the pixels. We are going to use a "for loop" in javascript to access each pixel's color channels and and convert the pixels to grayscale. The original image is below.

original image of flower

 

By using the average of colors(RGB) for every pixel independently:

var imageData = context.getImageData(imageX, imageY, image.width, image.height);
var dataArray = imageData.data;

for(var i = 0; i < dataArray.length; i += 4)
{
        var red = dataArray[i];
        var green = dataArray[i + 1];
        var blue = dataArray[i + 2];
        var alpha = dataArray[i + 3];
            
        var gray = (red + green + blue) / 3;
            
        dataArray[i] = gray;
        dataArray[i + 1] = gray;
        dataArray[i + 2] = gray;
        dataArray[i + 3] = alpha; // not changing the transparency
}

 

grayscale image using average formula


By using the luminance-preserving conversion method:

var imageData = context.getImageData(imageX, imageY, image.width, image.height);
var dataArray = imageData.data;

for(var i = 0; i < dataArray.length; i += 4)
{
        var red = dataArray[i];
        var green = dataArray[i + 1];
        var blue = dataArray[i + 2];
        var alpha = dataArray[i + 3];
            
        var gray = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
            
        dataArray[i] = gray;
        dataArray[i + 1] = gray;
        dataArray[i + 2] = gray;
        dataArray[i + 3] = alpha;
}

 

grayscale image using luminance-preserving

McAfee APAC


You might want to contribute to Qoncious.com:




Latest Videos