Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BufferedImage get single pixel brightness

I want to convert coloured image to a monochrome, i thought to loop all pixel, but I don't know how to test if they are bright or dark.

        for(int y=0;y<image.getHeight();y++){
            for(int x=0;x<image.getWidth();x++){
                int color=image.getRGB(x, y);
                // ???how to test if its is bright or dark?
            }
        }
like image 566
Tobia Avatar asked Dec 25 '22 14:12

Tobia


2 Answers

int color = image.getRGB(x, y);

// extract each color component
int red   = (color >>> 16) & 0xFF;
int green = (color >>>  8) & 0xFF;
int blue  = (color >>>  0) & 0xFF;

// calc luminance in range 0.0 to 1.0; using SRGB luminance constants
float luminance = (red * 0.2126f + green * 0.7152f + blue * 0.0722f) / 255;

// choose brightness threshold as appropriate:
if (luminance >= 0.5f) {
    // bright color
} else {
    // dark color
}
like image 133
Boann Avatar answered Jan 08 '23 22:01

Boann


I suggest first converting the pixel to grayscale, then applying a threshold for converting it pure black&white.

There are libraries that will do this for you, but if you want to learn how images are processed, here you are:

Colour to grayscale

There are various formulas for converting (see a nice article here), I prefer the "luminosity" one. So:

int grayscalePixel = (0.21 * pRed) + (0.71 * pGreen) + (0.07 * pBlue)

I cannot tell what API you are using to manipulate the image, so I left the formula above in general terms. pRed, pGreen and pBlue are the red, green and blue levels (values) for the pixel.

Grayscale to b/w

Now, you can apply a threshold with:

int bw = grayscalePixel > THRESHOLD? 1: 0;

or even:

boolean bw = grayscalePixel > THRESHOLD;

Pixel will be white if above threshold, black if below. Find the right THRESHOLD by experimenting a bit.

like image 27
Stefano Sanfilippo Avatar answered Jan 08 '23 23:01

Stefano Sanfilippo