39

I am trying to convert color image into grayscale using the average of red, green, blue. But it comes out with errors.

Here is my code

imgWidth = myBitmap.getWidth();
imgHeight = myBitmap.getHeight();
                    
for(int i =0;i<imgWidth;i++) {
    for(int j=0;j<imgHeight;j++) {
     int s = myBitmap.getPixel(i, j)/3;
     myBitmap.setPixel(i, j, s);
    }
}
                    
ImageView img = (ImageView)findViewById(R.id.image1);
img.setImageBitmap(myBitmap);

But when I run my application on Emulator, it's force close. Any idea?

I have solved my problem use the following code:

for(int x = 0; x < width; ++x) {
            for(int y = 0; y < height; ++y) {
                // get one pixel color
                pixel = src.getPixel(x, y);
                // retrieve color of all channels
                A = Color.alpha(pixel);
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
                // take conversion up to one single value
                R = G = B = (int)(0.299 * R + 0.587 * G + 0.114 * B);
                // set new pixel color to output bitmap
                bmOut.setPixel(x, y, Color.argb(A, R, G, B));
            }
        }
4

3 回答 3

94

你也可以这样做 :

    ColorMatrix matrix = new ColorMatrix();
    matrix.setSaturation(0); 
    imageview.setColorFilter(new ColorMatrixColorFilter(matrix));
于 2012-12-29T17:55:05.010 回答
32

尝试leparlon 之前的答案中的解决方案:

public Bitmap toGrayscale(Bitmap bmpOriginal)
    {        
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();    

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayscale;
    }
于 2011-12-05T06:09:23.900 回答
15

拉利特给出了最实际的答案。但是,您希望得到的灰色是红色、绿色和蓝色的平均值,并且应该像这样设置矩阵:

    float oneThird = 1/3f;
    float[] mat = new float[]{
            oneThird, oneThird, oneThird, 0, 0, 
            oneThird, oneThird, oneThird, 0, 0, 
            oneThird, oneThird, oneThird, 0, 0, 
            0, 0, 0, 1, 0,};
    ColorMatrixColorFilter filter = new ColorMatrixColorFilter(mat);
    paint.setColorFilter(filter);
    c.drawBitmap(original, 0, 0, paint);

最后,正如我之前遇到的将图像转换为灰度的问题 - 在所有情况下,视觉上最令人愉悦的结果是通过不取平均值来实现的,而是通过根据其感知亮度赋予每种颜色不同的权重,我倾向于使用这些值:

    float[] mat = new float[]{
            0.3f, 0.59f, 0.11f, 0, 0, 
            0.3f, 0.59f, 0.11f, 0, 0, 
            0.3f, 0.59f, 0.11f, 0, 0, 
            0, 0, 0, 1, 0,};
于 2011-12-05T09:19:52.600 回答