【问题标题】:Grayscaling large Bitmap image is slow灰度大位图图像很慢
【发布时间】:2014-07-21 17:38:00
【问题描述】:

我将图像加载到Bitmap 对象中。然后我想做的是对存储在Bitmap 对象中的图像进行灰度化处理。

我使用以下函数来做到这一点:

public static Bitmap grayscale(Bitmap src)
{
    // constant factors
    final double GS_RED = 0.299;
    final double GS_GREEN = 0.587;
    final double GS_BLUE = 0.114;

    // create output bitmap
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    // pixel information
    int A, R, G, B;
    int pixel;

    // get image size
    int width = src.getWidth();
    int height = src.getHeight();

    // scan through every single pixel
    for(int x = 0; x < width; ++x)
    {
        for(int y = 0; y < height; ++y)
        {
            // get one pixel color
            pixel = src.getPixel(x, y);

            // retrieve color of all channels
            A = Color.alpha(pixel);
            R = Color.red(pixel);
            G = Color.green(pixel);
            B = Color.blue(pixel);

            // take conversion up to one single value
            R = G = B = (int)(GS_RED * R + GS_GREEN * G + GS_BLUE * B);

            // set new pixel color to output bitmap
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }

    // return final image
    return bmOut;
}

它运行良好,但速度非常慢。不适用于像640x480 这样的“小”图像。但在我的情况下,图像是3264x2448。这实际上需要几秒钟才能完成操作...

所以我想知道像现在这样扫描每个像素是否真的是最好的方法?有没有更好更快的方法来转换图片的颜色?

【问题讨论】:

标签: android performance image-processing bitmap


【解决方案1】:

我怀疑扫描每个像素是最快的方式(它可能是最慢的)。

来自here 的一些重构代码看起来很有希望,因为它使用的是 Android API:

public Bitmap toGrayscale(Bitmap bmpOriginal) {     
    int height = bmpOriginal.getHeight();
    int 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2015-06-29
    • 2020-05-15
    • 2013-08-11
    • 2014-11-03
    • 2017-07-31
    相关资源
    最近更新 更多