How to calculate the pixels of the image area

Asked

Viewed 854 times

-1

I would like to calculate the pixels of the area of an image is not width and height because it is an irregular figure, I want to know how many pixels there are within this figure, example a triangle, if calculating the height x width of a triangle will not give the value of its area as it will take into account as a square. I’ve searched a lot on the Internet and I haven’t found anything to help me since thanks!

  • But after all, you want to count the pixels of the image or calculate the area of that image?

1 answer

0


Assuming that the image background is white and the image object (triangle, for example) is black, I imagine that it is necessary to go through each pixel of the image and check if the image color (RGB) is black. If it is, add 1 the area variable. At the end, you will have the amount of pixels that make up the image object (area).

It would be something like that:

public static double percentualBrancos(BufferedImage img)
{
    double area = 0;
    for (int y = 0; y < img.getHeight(); y++)
        for (int x = 0; x < img.getWidth(); x++)
        {
            Color pixel = new Color(img.getRGB(x, y));
            if ((pixel.getRed() == 0) && (pixel.getGreen() == 0) && (pixel.getBlue() == 0))
                area++;
        }
    return area; 
}
  • In fact this image that I will calculate was cut and saved in a file. png, thanks for the answer I will test your idea and see if it works on a cropped image, because the background of the image in . png is transparent.

  • So if the background is all the same color, in that "IF" of the code I answered, just test if the color is transparent. If not, area++, which is the image itself.

Browser other questions tagged

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