YUV420P转RGB24

大多数摄像机厂家的码流输出主流YUV420planar格式,即先连续存储所有像素点的Y,紧接着存储所有像素点的U,随后是所有像素点的V。
YUV420P转RGB24_第1张图片
但是在实际应用中发现虽同为YUV420p格式,仍存在一些差异。
如:大华摄像机的为YUV,而海康的为YVU,数据量一致,但UV数据位置反了。
所以在YUV转RGB的时候,采用OpenCV转换函数cv::cvtColor的转换类型也不一样,前者为CV_YUV2BGR_I420,后者为CV_YUV2BGR_YV12。

C++实现如下:

bool YUV420ToBGR24( unsigned char* pY, unsigned char* pU, unsigned char* pV, unsigned char* pRGB24, int width, int height)
{
	int yIdx, uIdx, vIdx, idx;
	int offset = 0;
	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j < width; j++)
		{
			yIdx = i * width + j;
			vIdx = (i / 4)* width + j / 2;
			uIdx = (i / 4)* width + j / 2;

			int R = (pY[yIdx] - 16) + 1.370805 * (pV[uIdx] - 128);                                                     // r分量	
			int G = (pY[yIdx] - 16) - 0.69825 * (pV[uIdx] - 128) - 0.33557 * (pU[vIdx] - 128);       // g分量
			int B = (pY[yIdx] - 16) + 1.733221 * (pU[vIdx] - 128);                                                     // b分量

			R = R < 255 ? R : 255;
			G = G < 255 ? G : 255;
			B = B < 255 ? B : 255;

			R = R < 0 ? 0 : R;
			G = G < 0 ? 0 : G;
			B = B < 0 ? 0 : B;

			pRGB24[offset++] = (unsigned char)R;
			pRGB24[offset++] = (unsigned char)G;
			pRGB24[offset++] = (unsigned char)B;

		}
	}
	return true;
}

具体参考
https://www.cnblogs.com/luoyinjie/p/7219319.html
https://blog.csdn.net/fuhanga123/article/details/51593794

你可能感兴趣的:(积累)