使用cv::cvtColor转yuv420sp到rgb有哪些
时间: 2024-02-03 10:12:57 浏览: 90
使用cv::cvtColor将YUV420SP转换为RGB可以有以下几种方式:
1. 使用COLOR_YUV2RGB_NV21或COLOR_YUV2RGB_NV12
```c++
cv::Mat yuvMat = cv::imread("input.jpg", cv::IMREAD_UNCHANGED);
cv::Mat rgbMat;
cv::cvtColor(yuvMat, rgbMat, cv::COLOR_YUV2RGB_NV21); // 或者使用 cv::COLOR_YUV2RGB_NV12
cv::imwrite("output.jpg", rgbMat);
```
2. 使用COLOR_YUV2BGR_NV21或COLOR_YUV2BGR_NV12,然后使用cv::cvtColor将BGR转换为RGB
```c++
cv::Mat yuvMat = cv::imread("input.jpg", cv::IMREAD_UNCHANGED);
cv::Mat bgrMat, rgbMat;
cv::cvtColor(yuvMat, bgrMat, cv::COLOR_YUV2BGR_NV21); // 或者使用 cv::COLOR_YUV2BGR_NV12
cv::cvtColor(bgrMat, rgbMat, cv::COLOR_BGR2RGB);
cv::imwrite("output.jpg", rgbMat);
```
3. 自己实现转换函数,参考下面的代码
```c++
void YUV420SP_to_RGB888(const unsigned char* yuv, unsigned char* rgb, int width, int height)
{
int frameSize = width * height;
int chromaSize = frameSize / 4;
const unsigned char* yData = yuv;
const unsigned char* uvData = yuv + frameSize;
for (int j = 0; j < height; j++) {
int yOffset = j * width;
int chromaOffset = (j / 2) * width / 2;
for (int i = 0; i < width; i++) {
int Y = yData[yOffset + i];
int V = uvData[chromaOffset + i / 2] - 128;
int U = uvData[frameSize + chromaOffset + i / 2] - 128;
int R = Y + 1.402 * V;
int G = Y - 0.344 * U - 0.714 * V;
int B = Y + 1.772 * U;
R = R < 0 ? 0 : (R > 255 ? 255 : R);
G = G < 0 ? 0 : (G > 255 ? 255 : G);
B = B < 0 ? 0 : (B > 255 ? 255 : B);
int index = (j * width + i) * 3;
rgb[index] = R;
rgb[index + 1] = G;
rgb[index + 2] = B;
}
}
}
cv::Mat yuv420sp_to_rgb(const unsigned char* yuv, int width, int height)
{
cv::Mat rgbMat(height, width, CV_8UC3);
unsigned char* rgbData = rgbMat.data;
YUV420SP_to_RGB888(yuv, rgbData, width, height);
return rgbMat;
}
```
阅读全文