问题
Im developing in android, and want to convert the byte-array from the camera's previewCallback, which is in YUV-format, to rgb-format.
I have used the function given in this answer: Getting frames from Video Image in Android
It works perfectly in java, but my problem is that I want to make the function in c++ (I'm using the ndk, and not very familiar with c++).
I have tried to create the function in c++, but it always makes strange results (eg the picture is all green).
Does anyone have a similar function or this function working in c++?
Thanks.
回答1:
Conversion from YUYV to RGB in C++:
unsigned char* rgb_image = new unsigned char[width * height * 3]; //width and height of the image to be converted
int y;
int cr;
int cb;
double r;
double g;
double b;
for (int i = 0, j = 0; i < width * height * 3; i+=6 j+=4) {
//first pixel
y = yuyv_image[j];
cb = yuyv_image[j+1];
cr = yuyv_image[j+3];
r = y + (1.4065 * (cr - 128));
g = y - (0.3455 * (cb - 128)) - (0.7169 * (cr - 128));
b = y + (1.7790 * (cb - 128));
//This prevents colour distortions in your rgb image
if (r < 0) r = 0;
else if (r > 255) r = 255;
if (g < 0) g = 0;
else if (g > 255) g = 255;
if (b < 0) b = 0;
else if (b > 255) b = 255;
rgb_image[i] = (unsigned char)r;
rgb_image[i+1] = (unsigned char)g;
rgb_image[i+2] = (unsigned char)b;
//second pixel
y = yuyv_image[j+2];
cb = yuyv_image[j+1];
cr = yuyv_image[j+3];
r = y + (1.4065 * (cr - 128));
g = y - (0.3455 * (cb - 128)) - (0.7169 * (cr - 128));
b = y + (1.7790 * (cb - 128));
if (r < 0) r = 0;
else if (r > 255) r = 255;
if (g < 0) g = 0;
else if (g > 255) g = 255;
if (b < 0) b = 0;
else if (b > 255) b = 255;
rgb_image[i+3] = (unsigned char)r;
rgb_image[i+4] = (unsigned char)g;
rgb_image[i+5] = (unsigned char)b;
}
This method assumes that your yuyv_image is an unsigned char* as well.
More information on YUYV can be found here
And for more clarification on YUYV --> RGB check out this
回答2:
Look at this: http://pastebin.com/mDcwqJV3
Fixed-point conversion from YUYV to RGB24
Also, some cameras return raw images in 'UYVY' byte orger, so make corresponding changes in the conversion function.
来源:https://stackoverflow.com/questions/9098881/convert-from-yuv-to-rgb-in-c-android-ndk