V.Vairaganesh
V.Vairaganesh

Reputation: 61

how to identify the background color of image captured from camera in android?

I want to capture an image from camera only when the background color is white.

Also suggest how to detect background color of an image ?

Is there any library for this?

Thanks in Advance

Upvotes: 1

Views: 1270

Answers (1)

Stepan Maksymov
Stepan Maksymov

Reputation: 2606

this long story cannot be short :)

make sure you have set in camera preview:

mCamera.getParameters().setPreviewFormat(ImageFormat.NV21);

you can get on camera callback your image:

Camera.PreviewCallback previewCb = new Camera.PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {
            if(camera == null || extractedColorsBackground.getVisibility() == View.VISIBLE)
                return;


            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = parameters.getPreviewSize();
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(0, info);
            if(mBitmapWidth == 0 || mBitmapHeight == 0) {
                    mBitmapWidth = size.width;
                    mBitmapHeight = size.height;
            }

            mCurrentImageRGB = new int[mBitmapWidth*mBitmapHeight];
            Recognize.decodeYUV420SP2(mCurrentImageRGB, data, mBitmapWidth, mBitmapHeight);

        }
    };

and transformer:

public static void decodeYUV420SP2(int[] rgb, byte[] yuv420sp, int width, int height) {

final int frameSize = width * height;

for (int j = 0, yp = 0; j < height; j++) {
    int uvp = frameSize + (j >> 1) * width, u = 0, v = 0;
    for (int i = 0; i < width; i++, yp++) {
        int y = (0xff & ((int) yuv420sp[yp])) - 16;
        if (y < 0)
            y = 0;
        if ((i & 1) == 0) {
            v = (0xff & yuv420sp[uvp++]) - 128;
            u = (0xff & yuv420sp[uvp++]) - 128;
        }

        int y1192 = 1192 * y;
        int r = (y1192 + 1634 * v);
        int g = (y1192 - 833 * v - 400 * u);
        int b = (y1192 + 2066 * u);

        if (r < 0)
            r = 0;
        else if (r > 262143)
            r = 262143;
        if (g < 0)
            g = 0;
        else if (g > 262143)
            g = 262143;
        if (b < 0)
            b = 0;
        else if (b > 262143)
            b = 262143;
        rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff);
    }
}

}

in mCurrentImageRGB - will be your int array of colors for this image. Now you can count how many is white.

more about white - if will be at least one #FFFFFF image this will be something amazing ) but you must count colors not white but very close to white, for example all that above #BBBBBB coz camera will not give you exact #FFFFFF )) you can see in callback what you get and you can act according situation.

Upvotes: 2

Related Questions