如何在android中将彩色图像位图转换为黑白图像位图?

时间:2013-11-28 12:45:20

标签: android bitmap

在我的名片阅读器Android应用程序中,我需要将彩色图像位图转换为黑色&用于OCR文本阅读的白色图像位图(非灰度图像)。所以请帮我把彩色图像位图转换为黑色& android中的白色图像位图。

3 个答案:

答案 0 :(得分:2)

这个问题很久以前,但我可能会帮助其他用户。 我也一直在寻找创建(快速)纯黑色和白色位图。

我的第一个方法是使用bitmap.getPixel()和bitmap.setPixel() 这花了大约8s(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;
}

答案 1 :(得分: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); 

答案 2 :(得分: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 });