Android图片灰度化二值化实现教程

1. 流程图

gantt
    title Android图片灰度化二值化实现流程
    section 整体流程
    源图片选取       :done, 2022-10-01, 1d
    图片灰度化处理  :done, after 源图片选取, 2d
    图片二值化处理  :done, after 图片灰度化处理, 2d

2. 步骤和代码

2.1 源图片选取

首先,你需要在res/drawable目录下放入一张图片,该图片将会被处理。

2.2 图片灰度化处理

// 获取图片
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_image);

// 将图片转化为灰度图
Bitmap greyBitmap = toGrayscale(originalBitmap);

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

    Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    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.3 图片二值化处理

// 将灰度图转化为二值图
Bitmap binaryBitmap = toBinary(greyBitmap);

private Bitmap toBinary(Bitmap bmpOriginal) {
    int width, height;
    height = bmpOriginal.getHeight();
    width = bmpOriginal.getWidth();

    Bitmap bmpBinary = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    for(int i=0; i<height; i++) {
        for(int j=0; j<width; j++) {
            int pixel = bmpOriginal.getPixel(j, i);
            int red = Color.red(pixel);
            int green = Color.green(pixel);
            int blue = Color.blue(pixel);
            int gray = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
            if(gray < 128) {
                bmpBinary.setPixel(j, i, Color.BLACK);
            } else {
                bmpBinary.setPixel(j, i, Color.WHITE);
            }
        }
    }

    return bmpBinary;
}

结束语

通过以上步骤,你可以实现Android图片的灰度化和二值化处理。希望这篇文章对你有帮助,如果有任何问题欢迎随时向我提问。加油!愿你在Android开发的道路上越走越远!