Count black pixels of an image region


I have the following question:

I have a script that I can select the coordinates of an area of an image:


Considering that I have a binária ( black and white ) image, how do I count the amount of black pixels in a certain area of that image.

For example, I want to know the amount of black pixels in the following image area:


Any ideas how I can do this?

asked by anonymous 11.10.2016 / 00:28

2 answers


If it's done in php try something like:

$numeroDePixels = abs(($se[0]-$id[0])*($se[1]-$id[1]));

In this code we have:


($ se [0] - $ id [0]) as the width of the area.


($ se [1] - $ id [1]) as the height of the area.


Area = Width * Height

And we use asb() to prevent the result from being negative.

11.10.2016 / 20:57

If I understand correctly, to count only the black pixels of the image area, you need to scan every pixel in the area to see if it is black or not. To manipulate the image, it must be on a canvas. link

var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

var contador = 0;
for(var i =; i < pos.bottom; i++)
    for(var j = pos.left; j < pos.right; j++){
        var pixelData = canvas.getContext('2d').getImageData(i, j, 1, 1).data; //valor de cores do pixel i,j em RGBA 
        if(pixeldata[0] == 0 && pixeldata[1] == 0 && pixeldata[2] == 0) //R, G e B == 0

PS: I did not test, thank you if you can test and give feedback

11.10.2016 / 21:26