【发布时间】:2016-08-17 22:34:23
【问题描述】:
在我的名片阅读器 android 应用程序中,我需要将 彩色图像位图转换为黑白图像位图(不是灰度图像) 以进行 OCR 文本读取。所以请帮我在android中将彩色图像位图转换为黑白图像位图。
【问题讨论】:
在我的名片阅读器 android 应用程序中,我需要将 彩色图像位图转换为黑白图像位图(不是灰度图像) 以进行 OCR 文本读取。所以请帮我在android中将彩色图像位图转换为黑白图像位图。
【问题讨论】:
这个问题很久以前了,但也许我可以帮助其他用户。 我还长期寻找(快速)创建纯黑白位图。
我的第一个方法是使用 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;
}
【讨论】:
您可以通过这种方式转换应用颜色过滤器的图像:
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);
【讨论】:
你需要在android中使用ColorMatrix和ColorFilterclass来转换成黑白。
使用这个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
});
【讨论】: