【opencv初学者】10、YUV图像转RGB

实现YUV_I420图像格式的转换,转换成RGB图像

/*---------------------YUV_I420图像转RGB图像--------------------------*/
	//输出976*656的YUV图像和BGR图像
	    Mat Image;
		Mat yuvImg;
		Mat test_yuv;

		Image = imread("C:/Users/xxx/Desktop/20220720-155604.jpeg");      //原图
		resize(Image, test_yuv, Size(976, 656));

		int w = test_yuv.cols;
		int h = test_yuv.rows;
		int buflen = w * h * 3 / 2;//
		int y_buflen = w * h;
		unsigned char* yuvbuf = new unsigned char[buflen];
		//unsigned char* y_yuvbuf = new unsigned char[y_buflen];
		//使用new关键字分配 buflen个unsigned char类型的内存,并用unsigned char类型的指针 yuvbuf 指向这块内存的首地址。

		FILE* pfile = fopen("C:/Users/xxx/Desktop/20220720-155604.yuv", "wb");//创建一个img.yuv的只写二进制文件,
		cv::cvtColor(test_yuv, yuvImg, COLOR_BGR2YUV_IYUV);
		Mat y_yuv = Mat(h, w, CV_8UC1);
		Mat yuv = cv::Mat(h * 3 / 2, w, CV_8UC1);
		Mat bgr24;

		memcpy(yuv.data, yuvImg.data, buflen * sizeof(unsigned char));//从存储区yuv.Img复制buflen * sizeof(unsigned char)个字节到yuvbuf。
		memcpy(yuvbuf, yuvImg.data, buflen * sizeof(unsigned char));
																	  //memcpy(y_yuv.data, yuvImg.data, y_buflen * sizeof(unsigned char));
		/*cv::imshow("YUV", yuvImg);
		cv::imshow("Y", y_yuv);
		cv::waitKey(1);*/

		cv::cvtColor(yuv, bgr24, COLOR_YUV2BGR_I420);
		imwrite("C:/Users/xxx/Desktop/new_yuv2bgr.jpg", bgr24);//生成YUV转BGR图像
		//cout << yuv << endl;
		//cout << y_yuv << endl;
		//保存yuv文件,包含所有通道
		fwrite(yuvbuf, buflen * sizeof(unsigned char), 1, pfile);//把yuvbuf指向的内容写入到一个字节大小为buflen。。。sizeof()的;1:元素个数;pfile
		fwrite(y_yuvbuf, y_buflen * sizeof(unsigned char), 1, y_pfile);
		fclose(pfile);//关闭流,刷新缓冲区  

你可能感兴趣的:(opencv,人工智能,计算机视觉)