简体   繁体   中英

Faster way to redraw a bitmap in android?

I'm processing an image for OCR, and I need to change the color of a bunch of pixels in a bitmap. Is there a faster method than setPixel and getPixel? Currently I'm just doing a for loop with a method that checks the input vs a bunch of RGB values and returns true if there's a match. Thank you very much!

    Bitmap img = myImage.copy(Bitmap.Config.ARGB_8888, true);;

    for (int w = 0; w < img.getWidth(); w++) {
        for (int h = 0; h < img.getHeight(); h++) {
            int value = img.getPixel(w, h);
            if (filter(value)) {
                img.setPixel(w, h, Color.rgb(0, 0, 0));
            } else img.setPixel(w, h, Color.rgb(255, 255, 255));
        }
    }

Just wanted to follow up and post code for if anyone finds this via search.

My code in the question was taking 3.4s on average, the code below using Gabe's advice is taking under 200ms. I also added a length variable because I read not calling array.length() every iteration could improve performance, but in testing there doesn't seem to be much of a benefit

    int width = img.getWidth();
    int height = img.getHeight();
    int length = width * height;
    int[] pixels = new int[width*height];
    img.getPixels(pixels, 0, width, 0, 0, width, height);

    for (int i = 0; i < length; i++) {
        if (filter(pixels[i])) {
            pixels[i] = Color.rgb(0, 0, 0);
        } else pixels[i] = Color.rgb(255, 255, 255);
    }

    img.setPixels(pixels, 0, width, 0, 0, width, height);

您可以随时尝试将图像分解为象限/网格,并为每个象限分配一个单独的线程。

I normally handle images with OpenCV on Jni. It is much faster than handling on Java. If you are not familliar with JNI, please reference this link. What is JNI Graphics or how to use it? You can also divide image and then process with multi-threading!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM