Count black pixels from a region of the image

Asked

Viewed 723 times

6

I have the following question:

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

https://jsfiddle.net/zauk0qLk/2/

Whereas I have an image binária (black and white), how do I count the amount of black pixels in a given 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 idea how I can do that?

  • I didn’t quite understand your tags. You want to count the dots with PHP or JS?

  • For me indifere, because I only need the return amount to handle in PHP, so it can be PHP or JS.

2 answers

4

If you’re going to do it in php try something like:

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

In this code we have:

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

($if[1]-$id[1]) as area height.

Area = Width * Height

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

  • Hello friend, all right? I believe that then we would count the pixels as one all and not filter to only one color, in the black case. Any suggestions? Thanks for the help!

3

If I understand correctly, to count only the pixels niggas from the image area, you need to scan each pixel of the area by checking whether it is black or not. To manipulate the image, it needs to be on a canvas. https://stackoverflow.com/questions/8751020/how-to-get-a-pixels-x-y-coordinate-color-from-an-image

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, I appreciate if you can test and give feedback

  • You’re right, I confess I hadn’t seen the example in jsfiddle.

  • Hello friend all right! Interesting your suggestion. Thanks for the help. I will do the tests here and soon share the result here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.