views:

75

answers:

4

I am trying to use one of these algorithms to convert a RGB image to grayscale :

The lightness method averages the most prominent and least prominent colors: (max(R, G, B) + min(R, G, B)) / 2.

The average method simply averages the values: (R + G + B) / 3.

The formula for luminosity is 0.21 R + 0.71 G + 0.07 B. But i get very weird results ! I know there are other ways to acheive this but is it possible to do this way ?

here is the code :

for(int i = 0 ; i < eWidth*eHeight;i++){
        int R = (pixels[i] >> 16) ;     //bitwise shifting
        int G = (pixels[i] >> 8) ;
        int B = pixels[i] ;
        int gray = (R + G + B )/ 3 ;
        pixels[i] = (gray << 16) | (gray << 8) | gray   ;
}
+1  A: 

What you made looks allright to me..

I once did this, in java, in much the same way. Getting the average of the 0-255 color values of RGB, to get grayscale, and it looks alot like yours.

public int getGray(int row, int col) throws Exception
{
     checkInImage(row,col);
     int[] rgb = this.getRGB(row,col);
     return  (int) (rgb[0]+rgb[1]+rgb[2])/3;
}
Thediabloman
+1  A: 

You can certainly modify each pixel in Java, but that's very inefficient. If you have the option, I would use a ColorMatrix. See the Android documentation for details: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/ColorMatrixSample.html

You could set the matrix' saturation to 0 to make it grayscale.

IF you really want to do it in Java, you can do it the way you did it, but you'll need to mask out each element first, i.e. apply & 0xff to it.

EboMike
thank you very much for your answer.I am suffering from lack of setpixel function indeed , and that was the my next question.
Tony
+2  A: 

You need to strip off the bits that aren't part of the component you're getting, especially if there's any sign extension going on in the shifts.

    int R = (q[i] >> 16) & 0xff ;     //bitwise shifting 
    int G = (q[i] >> 8) & 0xff ; 
    int B = q[i] & 0xff ; 
Mark Ransom
+1  A: 

I understand you are not asking for hoe to code this, but for algorithm?

There is no "correct" algorithm as per http://www.dfanning.com/ip_tips/color2gray.html

They use

Y = 0.3*R + 0.59*G + 0.11*B
Peter Knego
Those constants are the simplified versions of the ones chosen for NTSC color television: http://en.wikipedia.org/wiki/YUV. I've never seen any evidence that they map well to human perception, but it's probably better than a straight average.
Mark Ransom