如何在Android/Java中加速图像处理?

3

我在跟随一些Java代码进行位图图像处理,发现这对用户来说非常耗时。

如何通过代码更快地完成这项工作?

目前逐像素处理的速度太慢了。

我在某处读到过先将其存储为2d数组的方法?矩阵

public static Bitmap createContrast(Bitmap src, double value) {
    // image size
    int width = src.getWidth();
    int height = src.getHeight();
    // create output bitmap
    Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
    // color information
    int A, R, G, B;
    int pixel;
    // get contrast value
    double contrast = Math.pow((100 + value) / 100, 2);

    // scan through all pixels
    for(int x = 0; x < width; ++x) {
        for(int y = 0; y < height; ++y) {
            // get pixel color
            pixel = src.getPixel(x, y);
            A = Color.alpha(pixel);
            // apply filter contrast for every channel R, G, B
            R = Color.red(pixel);
            R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
            if(R < 0) { R = 0; }
            else if(R > 255) { R = 255; }

            G = Color.red(pixel);
            G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
            if(G < 0) { G = 0; }
            else if(G > 255) { G = 255; }

            B = Color.red(pixel);
            B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
            if(B < 0) { B = 0; }
            else if(B > 255) { B = 255; }

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

    // return final image
    return bmOut;
}

如果目标是Android 3.0及以上版本,则使用RenderScript。 - xandy
我看到了一个O(n^2)的循环;对于大图片来说,这总是会很慢。你的优化可能需要通过重新审视你的算法来实现。 - Makoto
1
如果你愿意学习OpenGL/GLSL,你可能可以将算法的速度提高数个数量级。 - Tim
1个回答

0
我建议使用getPixels和setPixels,这样您就可以直接操作数组。我没有运行过这个程序,但它应该能给您一个想法:
int[] pixels = new int[width * height];
bmOut.getPixels(pixels, 0, width, 0, 0, width, height);
// scan through all pixels
for(int i = 0; i < width * height; i++) {
    // get pixel color
    // pixel = src.getPixel(x, y);
    pixel = pixels[i];
    A = Color.alpha(pixel);
    // apply filter contrast for every channel R, G, B
    R = Color.red(pixel);
    R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
    if(R < 0) { R = 0; }
    else if(R > 255) { R = 255; }

    G = Color.green(pixel);
    G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
    if(G < 0) { G = 0; }
    else if(G > 255) { G = 255; }

    B = Color.blue(pixel);
    B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
    if(B < 0) { B = 0; }
    else if(B > 255) { B = 255; }

    // set new pixel color to output bitmap
    pixels[i] = Color.argb(A, R, G, B);
}
bmOut.setPixels(pixels, 0, width, 0, 0, width, height);

1
我还会用预先计算好的数组查找来替换 (int)(((((RGB / 255.0) - 0.5) * contrast) + 0.5) * 255.0) - Ken Y-N

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接