2

我正在尝试使用其中一种算法将 RGB 图像转换为灰度:

亮度方法平均最突出和最不突出的颜色:(max(R, G, B) + min(R, G, B)) / 2。

平均方法只是对值进行平均:(R + G + B) / 3。

光度的公式是 0.21 R + 0.71 G + 0.07 B。

但我得到了非常奇怪的结果!我知道还有其他方法可以实现这一点,但可以这样做吗?

这是代码:

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   ;
}
4

4 回答 4

2

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 ; 
于 2010-10-28T18:21:35.170 回答
1

我知道你不是要求锄头来编码这个,而是算法?

根据http://www.dfanning.com/ip_tips/color2gray.html没有“正确”算法

他们使用

Y = 0.3*R + 0.59*G + 0.11*B
于 2010-10-28T18:24:22.580 回答
1

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;
}
于 2010-10-28T18:17:08.193 回答
1

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.

于 2010-10-28T18:17:43.477 回答