Question

Actually I'm working on some image processing project and got struck somewhere. I have to convert the colored image to grey scale and for this i have extracted the values of RED, GREEN, BLUE component of a pixel using GETRGB() n now I want to set the RGB value of that pixel equal to the average of its RGB component. The RGB components are stored in INT variables respectively, so can u help me to set the average of this RGB components to the original pixel value?? The part of the code is :

           rgbArray=new int[w*h];
           buffer.getRGB(0, 0, width, height, rgbArray , 0,width );
           int a,r,g,b; 
           for(int i = 0 ; i<w*h; i++)
            { 
              r = (0x00ff0000 & rgbArray[i]) >> 16;
              g = (0x0000ff00 & rgbArray[i]) >> 8;
              b = (0x000000ff & rgbArray[i]);
              rgbArray[i] = (r+g+b)/3;
            }
           buffer.setRGB(0, 0, width, height, rgbArray , 0,width);

but this is not giving me a grey image. Can u tell where i am doing a mistake.

No correct solution

OTHER TIPS

It is not clear what you want to do. If you are trying to produce a gray color I suggest referring to the following page: http://www.tayloredmktg.com/rgb/ which shows rgb codes for different shades of gray.

If you are trying to get a translucent image you have to use the alpha channel (RGBA commands) in java. You can also get translucency by compositing the underlying image with your current image in special ways but that is MUCH harder than using alpha channel.

Your code does not pack the grayscale level back into each color component. Also, as I said in my comment to the question, conversion to grayscale needs to consider the human eye's sensitivity to each color component. A typical formula for obtaining the gray level is

G = 0.30 * R + 0.59 * G + 0.11 * B

as this Wikipedia article states.

So your for loop should look like this:

for(int i = 0 ; i<w*h; i++)
{
    a = (0xff000000 & rgbArray[i]);
    r = (0x00ff0000 & rgbArray[i]) >> 16;
    g = (0x0000ff00 & rgbArray[i]) >> 8;
    b = (0x000000ff & rgbArray[i]);
    int gray = (int)(0.30 * r + 0.59 * g + 0.11 * b);
    if ( gray < 0 ) gray = 0;
    if ( gray > 255 ) gray = 255;
    rgbArray[i] = a | ( gray << 16 ) | ( gray << 8 ) | gray;
}

You can, of course, declare gray outside of the loop, like you did with r, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top