首页 > 代码库 > cv::Mat到YUV420的转换

cv::Mat到YUV420的转换

某些特定场合我们会经常遇到yuv420格式的视频文件,这种视频帧无法直接用于opencv,故而,需要进行格式转换;幸运的是,opencv提供了rgb到yuv420的格式转换函数;下面给出基本用法;


函数1:读取avi格式的视频文件,转换成Yuv420格式,并写入文件;

void WriteYuv()
{
	cv::VideoCapture vc;
	bool flag = vc.open("S1000008.avi");
	if (!flag)
	{
		printf("avi file open error \n");
		system("pause");
		exit(-1);
	}

	int frmCount = vc.get(CV_CAP_PROP_FRAME_COUNT);
	frmCount -= 5;
	printf("frmCount: %d \n", frmCount);

	int w = vc.get(CV_CAP_PROP_FRAME_WIDTH);
	int h = vc.get(CV_CAP_PROP_FRAME_HEIGHT);
	int bufLen = w*h*3/2;
	unsigned char* pYuvBuf = new unsigned char[bufLen];
	FILE* pFileOut = fopen("result.yuv", "w+");
	if (!pFileOut)
	{
		printf("pFileOut open error \n");
		system("pause");
		exit(-1);
	}
	printf("pFileOut open ok \n");
	
	for (int i=0; i<frmCount; i++)
	{
		printf("%d/%d \n", i+1, frmCount);

		cv::Mat srcImg;
		vc>>srcImg;

		cv::imshow("img", srcImg);
		cv::waitKey(1);

		cv::Mat yuvImg;
		cv::cvtColor(srcImg, yuvImg, CV_BGR2YUV_I420);
		memcpy(pYuvBuf, yuvImg.data, bufLen*sizeof(unsigned char));

		fwrite(pYuvBuf, bufLen*sizeof(unsigned char), 1, pFileOut);
	}

	fclose(pFileOut);
	delete[] pYuvBuf;
}

函数二,读取yuv420格式的文件,转换成cv::Mat格式,并予以显示:

void DisplayYUV()
{
	int w = 1280;
	int h = 720;
	printf("yuv file w: %d, h: %d \n", w, h);

	FILE* pFileIn = fopen("result.yuv", "rb+");
	int bufLen = w*h*3/2;
	unsigned char* pYuvBuf = new unsigned char[bufLen];
	int iCount = 0;


	for(int i=0; i<200; i++)
	{
		fread(pYuvBuf, bufLen*sizeof(unsigned char), 1, pFileIn);

		cv::Mat yuvImg;
		yuvImg.create(h*3/2, w, CV_8UC1); 
		memcpy(yuvImg.data, pYuvBuf, bufLen*sizeof(unsigned char));
		cv::Mat rgbImg;
		cv::cvtColor(yuvImg, rgbImg, CV_YUV2BGR_I420);

		cv::imshow("img", yuvImg);
		cv::waitKey(1);

		printf("%d \n", iCount++);
	}

	delete[] pYuvBuf;


	fclose(pFileIn);
}