2013-11-28 90 views

回答

0

您需要在android中使用ColorMatrixColorFilter类才能转换为黑白。 使用此ColorMatrix - ColorMatrix cm1 = new ColorMatrix(new float[]{0.5f,0.5f,0.5f,0,0, 0.5f,0.5f,0.5f,0,0, 0.5f,0.5f,0.5f,0,0, 0,0,0,1,0,0, 0,0,0,0,1,0 });

1

你可以运用这种方式的彩色滤光片的图像转换:

Bitmap bwBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
Canvas canvas = new Canvas(bwBitmap); 
//set contrast 
ColorMatrix contrastMatrix = new ColorMatrix(); 
//change contrast 
float contrast = 50.f; 
float shift = (-.5f * contrast + .5f) * 255.f; 
contrastMatrix .set(new float[] { 
     contrast , 0, 0, 0, shift , 
     0, contrast , 0, 0, shift , 
     0, 0, contrast , 0, shift , 
     0, 0, 0, 1, 0 }); 
//apply contrast 
Paint contrastPaint = new Paint(); 
contrastPaint.setColorFilter(new ColorMatrixColorFilter(contrastMatrix)); 
canvas.drawBitmap(colorBitmap, 0, 0, contrastPaint); 

//set saturation 
ColorMatrix saturationMatrix = new ColorMatrix(); 
saturationMatrix.setSaturation(0); //you set color saturation to 0 for b/w 
//apply new saturation 
Paint saturationPaint = new Paint(); 
saturationPaint.setColorFilter(new ColorMatrixColorFilter(saturationPaint)); 
canvas.drawBitmap(colorBitmap, 0, 0, saturationPaint); 
+1

如果我在上面的代码中使用它会产生灰度图像,而不是纯黑白图像,在我的应用程序中需要读取名片/名片中的文字。请帮帮我。 –

+0

通常一个灰度图像被认为是黑白。你想要的是一个高对比度的灰度图像,这样黑灰色变成黑色,浅灰色变成白色。您可以实现更改图像对比度。我编辑了我的评论,插入代码来设置一个ColorMatrix。尝试改变对比度值,为您找到最佳结果。 –

+0

如果我使用上面的ma.set()方法,它将会将grasy-scale图像与对比度一起更改为彩色图像。请帮帮我。 –

1

这个问题很久以前,但可能我可以帮助其他用户。 我也有很长的搜索创建(快速)纯黑白位图。

我的第一个梅索德使用bitmap.getPixel()和bitmap.setPixel() 这花了大约8秒(832 X 1532) 新方法花了0.4秒!感谢因素20!

现在我加载的所有像素int数组和走那么通过所有像素的getPixels用(..)和中的setPixels(..): 这里我的方法:

public static Bitmap createBlackAndWhite(Bitmap src) { 
    int width = src.getWidth(); 
    int height = src.getHeight(); 

    Bitmap bmOut = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 

    final float factor = 255f; 
    final float redBri = 0.2126f; 
    final float greenBri = 0.2126f; 
    final float blueBri = 0.0722f; 

    int length = width * height; 
    int[] inpixels = new int[length]; 
    int[] oupixels = new int[length]; 

    src.getPixels(inpixels, 0, width, 0, 0, width, height); 

    int point = 0; 
    for(int pix: inpixels){ 
     int R = (pix >> 16) & 0xFF; 
     int G = (pix >> 8) & 0xFF; 
     int B = pix & 0xFF; 

     float lum = (redBri * R/factor) + (greenBri * G/factor) + (blueBri * B/factor); 

     if (lum > 0.4) { 
      oupixels[point] = 0xFFFFFFFF; 
     }else{ 
      oupixels[point] = 0xFF000000; 
     } 
     point++; 
    } 
    bmOut.setPixels(oupixels, 0, width, 0, 0, width, height); 
    return bmOut; 
} 
相关问题