Raster Threshold Faster

I'm trying to write a method that will take Bitmap

and force it into a strict black and white image (no grayscale).

First, I pass the bitmap to a method that grayscale it using colormatrix

:

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

    Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    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;
}

      

which works well and quickly.

then I pass it to another method to make the grayscale image get a 2-color image (black and white), this method works but obviously it goes through every pixel and takes a long time:

public Bitmap toStrictBlackWhite(Bitmap bmp){
        Bitmap imageOut = bmp;
        int tempColorRed;
        for(int y=0; y<bmp.getHeight(); y++){
            for(int x=0; x<bmp.getWidth(); x++){
                tempColorRed = Color.red(imageOut.getPixel(x,y));
                Log.v(TAG, "COLOR: "+tempColorRed);

                if(imageOut.getPixel(x,y) < 127){
                    imageOut.setPixel(x, y, 0xffffff);
                }
                else{
                    imageOut.setPixel(x, y, 0x000000);
                }               
            }
        } 
        return imageOut;
    }

      

Does anyone know a more efficient way to do this?

+3


source to share


2 answers


Do not use getPixel()

and setPixel()

.



Use getPixels()

which will return a multidimensional array of all pixels. Do your operations locally on that array, then use setPixels()

to return the modified array. It will be much faster.

+3


source


Have you tried something like converting it to a byte array (see answer here )?



And, as I am looking at this, the Android developer link on Bitmap handling might help you.

+1


source







All Articles