Count black pixels of an image region

6

I have the following question:

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

link

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:

{"se":[175,145],"sd":[229,145],"ie":[175,221],"id":[229,221]}

Any ideas how I can do this?

    
asked by anonymous 11.10.2016 / 00:28

2 answers

4

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
3

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 = pos.top; 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
            contador++;
    }

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

    
11.10.2016 / 21:26