使用彩色矩阵仅使用蓝色通道将彩色位图转换为灰度图像



我需要在Android中只使用蓝色通道对位图进行灰度处理。我设法通过使用颜色矩阵去除了绿色和红色通道,但当我将该矩阵的饱和度设置为0时,它忽略了之前对红色和绿色通道所做的更改。

有办法完成我的任务吗?遍历整个像素阵列不是一种选择,因为它太慢了。

我使用的是这段代码:

public Bitmap ConvertToGrayscale(Bitmap bitmap) {
    int height = super.getHeight();
    int width = super.getWidth();
    float[] arrayForColorMatrix = new float[] {0, 0, 0, 0, 0,
                                               0, 0, 0, 0, 0,
                                               0, 0, 1, 0, 0,
                                               0, 0, 0, 1, 0};
    Bitmap.Config config = bitmap.getConfig();
    Bitmap grayScaleBitmap = Bitmap.createBitmap(width, height, config);
    Canvas c = new Canvas(grayScaleBitmap);
    Paint paint = new Paint();
    ColorMatrix matrix = new ColorMatrix(arrayForColorMatrix);
    matrix.setSaturation(0);
    ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
    paint.setColorFilter(filter);
    c.drawBitmap(bitmap, 0, 0, paint);
    return grayScaleBitmap;
}

从蓝色通道获得灰度图像的正确矩阵如下:

float[] arrayForColorMatrix = new float[] {0, 0, 1, 0, 0,
                                           0, 0, 1, 0, 0,
                                           0, 0, 1, 0, 0,
                                           0, 0, 0, 1, 0};

来自Android文档:

当应用于颜色[r,g,b,a]时,所得颜色计算为(箝位后):

R' = a*R + b*G + c*B + d*A + e;
G' = f*R + g*G + h*B + i*A + j;
B' = k*R + l*G + m*B + n*A + o;
A' = p*R + q*G + r*B + s*A + t;

使用我的arrayForColorMatrix,我获得RGB颜色分量的每个值的蓝色值,这会产生基于蓝色通道的灰度位图。

最新更新