Robert Chen
Robert Chen

Reputation: 41

Android Yuv420sp to ARGB in OpenCV

I am trying to send a raw image from the previewcallback from the phone to PC. The PC will then process the image. I am use OpenCV library to do the image processing. At the moment i just write a function in previewcallback to save the byte array to a file, and copy the file to pc and I wrote a simple program to first read in the file and save it into memeory and then directly copy the data to the IplImage.imageData. But I always get a garbage image.

I use this function I found on net to do the converstion between YUV420SP to ARGB. Thanks for your help.

void decodeYUV420SP(int* rgb, char* yuv420sp, int width, int height) {
    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);
        }
    }
}

Upvotes: 4

Views: 5955

Answers (4)

user1843643
user1843643

Reputation: 11

Based on my understanding, if an image that is 640*480. In the YUV420 byte buffer, the first 640*480 bytes will be correspond to the Y part. And followed by 320*480 bytes of Cb and Cr interleavely, so first 640*480 byte of Y and the following 320*480 byte of CbCr, which are down sampled in a 2-by-2 grid

Upvotes: 0

Rui Marques
Rui Marques

Reputation: 8904

You can use OpenCV4Android converters:

Imgproc.cvtColor(mYuv, mRgba, Imgproc.COLOR_YUV420sp2RGBA);

Upvotes: 2

alistair
alistair

Reputation: 1172

Did you manage to do this? If not take a look at the android-opencv project - they have a method for android yuv to bgr.

Upvotes: 0

Martin Beckett
Martin Beckett

Reputation: 96119

YUV420 images are an odd shape, the Y (luminescence) part is half the width and heigth of the image but this is followed by the Cr and Cb parts at half width but quarter height.
Normally they aren't displayed directly so nobody cares about the odd packing.

The result is a color image with only 1.5bytes/pixel instead of for rgb

Upvotes: 2

Related Questions