Converting a colored image to grayscale image in Java

Viewed 957

I want to convert a colored image to grayscale without too much-predefined methods.

the code of reading the colored image is here

The main method:

BufferedImage img = null;
try {
    img = ImageIO.read(new File(IMG));

    int[][] pixelData = new int[img.getHeight() * img.getWidth()][3];
    int[] rgb;

    int counter = 0;
    for (int i = 0; i < img.getWidth(); i++) {
        for (int j = 0; j < img.getHeight(); j++) {
            rgb = getPixelData(img, i, j);

            for (int k = 0; k < rgb.length; k++) {
                pixelData[counter][k] = rgb[k];
            }
            counter++;
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

Another method:

private static int[] getPixelData(BufferedImage img, int x, int y) {
    int argb = img.getRGB(x, y);
    int rgb[] = new int[] {
        (argb >> 16) & 0xff, //red
        (argb >>  8) & 0xff, //green
        (argb      ) & 0xff  //blue
    };

    System.out.println("rgb: " + rgb[0] + " " + rgb[1] + " " + rgb[2]);
    return rgb;
}

I need to convert the output to grayscale... Here is some of the output

 rgb: 255 255 255
 rgb: 255 255 255
 rgb: 255 255 255
 rgb: 255 255 255
 rgb: 255 255 255
 rgb: 255 255 255

I need to check every pixel for it's RGB and convert it into grayscale.

1 Answers

Quick and dirty method would be:

    int avg = (( rgb[0] + rgb[1] + rgb[2]) / 3);

    int grey_rgb = 0;
    for(int i = 0; i < 4; i++) {
        grey_rgb <<= 8;
        grey_rgb |= avg & 0xFF;
    }

    img.setRGB(x, y, grey_rgb );

A grey nuance is obtained when all its RGB components contain the same value (ex. 240 240 240). In order to achieve that, we simply need an average of numeric representation of colour's RGB components.

For more advanced algorithms please check this: tannerhelland.com/3643/grayscale-image-algorithm-vb6 .

Related