天天看点

opencv yuv420与Mat互转

项目用到opencv 融合图片的功能,经过一天的调试,达到预期目标,先将如何调用opencv库实现YUV42与Mat互转记录下来。

一.下载opencv编译的库下载地址是:http://opencv.org/releases.html ,根据需要选择相应的版本,我们项目中用到的版本是2.4.13。

二.下载Eigen库,下载地址是:http://eigen.tuxfamily.org/index.php?title=Main_Page,将Eigen库解压到本地,引用opencv库是要用到

     Eigen库(例如解压后的目录是F:\vs2015-project\CGFusePlay\lib\eigen-eigen-da9b4e14c255,将路径F:\vs2015-project\CGFusePlay\lib\eigen-eigen-da9b4e14c255\Eigen

添加到编译工程中),否则会编译不通过。

三,将YUV420数据与Mat互转:

mainYUuvImage.create( mainHeight * 3 / 2, mainWidth, CV_8UC1);
	CopyYUVToImage(mainYUuvImage.data, mainY, mainU, mainV, mainWidth, mainHeight);
	cv::Mat mainRgbImage;
	cv::cvtColor(mainYUuvImage, mainRgbImage, CV_YUV2BGR_I420);
					
	cv::Mat subYuvImage;
	subYuvImage.create(subHeight * 3 / 2,subWidth,  CV_8UC1);
	CopyYUVToImage(subYuvImage.data, subY, subU, subV, subWidth, subHeight);
	cv::Mat subRgbImage;
	cv::cvtColor(subYuvImage, subRgbImage, CV_YUV2BGR_I420);

	double alpha = 0.5;
	cv::Mat dstRgbImage;
	
	cv::Mat dstYuvImage;
	cv::cvtColor(dstRgbImage, dstYuvImage, CV_BGR2YUV_I420);

	CopyImageToYUV(mainY, mainU, mainV, dstYuvImage.data,mainWidth, mainHeight);      
static void CopyYUVToImage(uchar * dst ,uint8_t *pY, uint8_t *pU , uint8_t *pV,int width, int height)
{
  uint32_t size = width * height;
  memcpy(dst, pY, size);
  memcpy(dst + size, pU, size /4);
  memcpy(dst + size + size /4, pV, size / 4);
}

static void CopyImageToYUV(uint8_t *pY, uint8_t *pU, uint8_t *pV, uchar * src ,int width, int height)
{
  uint32_t size = width * height;
  memcpy(pY, src, size);
  memcpy(pU, src + size, size / 4);
  memcpy(pV, src + size + size / 4, size / 4);
}
      

  

如需交流,可以加QQ群1038388075,766718184,或者QQ:350197870

 博主提供ffmpeg 视频教程 播放地址: http://www.iqiyi.com/u/1426749687

视频下载地址:http://www.chungen90.com/?news_33/

 Demo下载地址: http://www.chungen90.com/?news_34