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

#include 
#include
#include
using namespace std;
using namespace cv;
int main()
{


		Mat Image;
		Mat yuvImg;
		Mat test_yuv;
	
		Image = imread("C:/Users/xxx/Desktop/20220720-155604.jpeg");      //原图
		resize(Image, test_yuv, Size(976, 656));
		//imshow("xiugaihou", test_yuv);
		//cv::waitKey(0);
		//cv::imwrite("C:/Users/xxx/Desktop/656976.jpg", test_yuv);
		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);

		memcpy(yuvbuf, yuvImg.data, buflen * sizeof(unsigned char));//从存储区yuv.Img复制buflen * sizeof(unsigned char)个字节到yuvbuf。
		memcpy(y_yuv.data, yuvImg.data, y_buflen * sizeof(unsigned char));
		cv::imshow("YUV", yuvImg);
	    cv::imshow("Y", y_yuv);
	    cv::waitKey(1);
		//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,计算机视觉,人工智能)