YUV420P轉RGB24

大多數攝像機廠家的碼流輸出主流YUV420planar格式,即先連續存儲所有像素點的Y,緊接着存儲所有像素點的U,隨後是所有像素點的V。
在這裏插入圖片描述
但是在實際應用中發現雖同爲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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章