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(-);
} int frmCount = vc.get(CV_CAP_PROP_FRAME_COUNT);
frmCount -= ;
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*/;
unsigned char* pYuvBuf = new unsigned char[bufLen];
FILE* pFileOut = fopen("result.yuv", "w+");
if (!pFileOut)
{
printf("pFileOut open error \n");
system("pause");
exit(-);
}
printf("pFileOut open ok \n"); for (int i=; i<frmCount; i++)
{
printf("%d/%d \n", i+, frmCount); cv::Mat srcImg;
vc>>srcImg; cv::imshow("img", srcImg);
cv::waitKey(); cv::Mat yuvImg;
cv::cvtColor(srcImg, yuvImg, CV_BGR2YUV_I420);
memcpy(pYuvBuf, yuvImg.data, bufLen*sizeof(unsigned char)); fwrite(pYuvBuf, bufLen*sizeof(unsigned char), , pFileOut);
} fclose(pFileOut);
delete[] pYuvBuf;
}

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

void DisplayYUV()
{
int w = ;
int h = ;
printf("yuv file w: %d, h: %d \n", w, h); FILE* pFileIn = fopen("result.yuv", "rb+");
int bufLen = w*h*/;
unsigned char* pYuvBuf = new unsigned char[bufLen];
int iCount = ; for(int i=; i<; i++)
{
fread(pYuvBuf, bufLen*sizeof(unsigned char), , pFileIn); cv::Mat yuvImg;
yuvImg.create(h*/, 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(); printf("%d \n", iCount++);
} delete[] pYuvBuf; fclose(pFileIn);
}

===================================

原贴地址:https://blog.csdn.net/carson2005/article/details/38351717

上一篇:FFMPEG结构体分析:AVFrame(解码后的数据)


下一篇:FFMPEG 实现 YUV,RGB各种图像原始数据之间的转换(swscale)