Android:将彩色图像转换为灰度

时间:2011-12-05 05:54:42

标签: android grayscale

大家好我需要你的帮助,我尝试使用红色,绿色,蓝色的平均值将彩色图像转换为灰度。但它出现了错误,

这是我的代码

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);

但是当我在模拟器上运行我的应用程序时,它会强制关闭。有什么想法吗?

我已使用以下代码解决了我的问题:

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

3 个答案:

答案 0 :(得分:73)

您也可以这样做:

    ColorMatrix matrix = new ColorMatrix();
    matrix.setSaturation(0);

    ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
    imageview.setColorFilter(filter);

答案 1 :(得分:31)

尝试解决方案from this previous answer by 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;
    }

答案 2 :(得分:12)

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

    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,};
相关问题