Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this more efficient in Android?

Tags:

android

I have this piece of code that takes the bitmap of a CameraPreview from a TextureView and renders it on a ImageView.

public void onSurfaceTextureUpdated(SurfaceTexture surface) {
    // Invoked every time there's a new Camera preview frame

    bmp = mTextureView.getBitmap();
    bmp2 = bmp.copy(bmp.getConfig(),true);

    for(int x=0;x<bmp.getWidth();x++){
        for(int y=0;y<bmp.getHeight();y++){
            //Log.i("Pixel RGB (Int)", Integer.toString(bmp.getPixel(x,y)));
            if(bmp.getPixel(x,y) < -8388608){
                bmp2.setPixel(x,y,Color.WHITE);
            }else{
                bmp2.setPixel(x,y,Color.BLACK);
            }
        }
    }

    mImageView.setImageBitmap(bmp2);
}

So basically I will be applying real-time image-processing on whatever the camera shows. For now it just back and whites pixels. It is a bit slow now, and the bitmap has only a width and height of ~250 pixels.

Is this the recommended way of doing this ?

like image 444
Trt Trt Avatar asked Jun 11 '15 14:06

Trt Trt


1 Answers

To filter bitmaps efficiently you can use ColorMatrixColorFilter. For example to make your image black & white use this code:

ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);

float m = 255f;
float t = -255*1.2f;
ColorMatrix threshold = new ColorMatrix(new float[] {
            m, 0, 0, 1, t,
            0, m, 0, 1, t,
            0, 0, m, 1, t,
            0, 0, 0, 1, 0
});

// Convert to grayscale, then scale and clamp
colorMatrix.postConcat(threshold);

ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
imageView.setColorFilter(filter);

Basically you have to transform the color range so values equal to (color) and (color+1) are (0) and (1). That's why I'm multiplying color by 255 and shifting. You may want to play with these parameters to get the right result.

Check out the slides here: http://chiuki.github.io/android-shaders-filters/#/16

like image 160
Zielony Avatar answered Oct 24 '22 05:10

Zielony