【opencv初学者】11、RGB图像转NV21

#include 
#include 
#include 
#include 
#include 
#include 
#include 



void RGB2NV21()
{
	//const char* filename = "yuv.yuv";
	cv::Mat Img = cv::imread("RGB.jpg");
	FILE* fp;
	errno_t err = fopen_s(&fp, "yuv.yuv", "wb");
	//FILE* fp = fopen_s("yuv.yuv", "wb");
	if (Img.empty())
	{
		std::cout << "empty!check your image";
		return;
	}
	int cols = Img.cols;
	int rows = Img.rows;

	int Yindex = 0;
	int UVindex = rows * cols;

	unsigned char* yuvbuff = new unsigned char[1.5 * rows * cols];

	cv::Mat NV21(rows + rows / 2, cols, CV_8UC1);
	//cv::Mat OpencvYUV;
	///*cv::Mat OpencvImg;
	//cv::cvtColor(Img, OpencvYUV, cv::ColorConversionCodes::COLOR_BGR2YUV_YV12);*/

	int UVRow{ 0 };
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cols; j++)
		{
			uchar* YPointer = NV21.ptr<uchar>(i);

			int B = Img.at<cv::Vec3b>(i, j)[0];
			int G = Img.at<cv::Vec3b>(i, j)[1];
			int R = Img.at<cv::Vec3b>(i, j)[2];

			//计算Y的值
			int Y = (77 * R + 150 * G + 29 * B) >> 8;
			YPointer[j] = Y;
			yuvbuff[Yindex++] = (Y < 0) ? 0 : ((Y > 255) ? 255 : Y);
			uchar* UVPointer = NV21.ptr<uchar>(rows + i / 2);
			//计算U、V的值,进行2x2的采样
			if (i % 2 == 0 && (j) % 2 == 0)
			{
				int U = ((-44 * R - 87 * G + 131 * B) >> 8) + 128;
				int V = ((131 * R - 110 * G - 21 * B) >> 8) + 128;
				UVPointer[j] = V;
				UVPointer[j + 1] = U;
				yuvbuff[UVindex++] = (V < 0) ? 0 : ((V > 255) ? 255 : V);
				yuvbuff[UVindex++] = (U < 0) ? 0 : ((U > 255) ? 255 : U);
			}
		}
	}
	for (int i = 0; i < 1.5 * rows * cols; i++)
	{
		fwrite(&yuvbuff[i], 1, 1, fp);
	}
	fclose(fp);
	std::cout << "write to file ok!" << std::endl;
	std::cout << "srcImg: " << "rows:" << Img.rows << "cols:" << Img.cols << std::endl;
	std::cout << "NV21: " << "rows:" << NV21.rows << "cols:" << NV21.cols << std::endl;
	//std::cout << "opencv_YUV: " << "rows:" << OpencvYUV.rows << "cols:" << OpencvYUV.cols << std::endl;

	cv::imshow("src", Img);//原图
	cv::imshow("YUV", NV21);//转换后的图片
	//cv::imshow("opencv_YUV", OpencvYUV); //opencv转换后的图片
	cv::imwrite("NV21.jpg", NV21);
	cv::waitKey(30000);
}

int main()
{
	RGB2NV21();
	return 0;
}

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