我是靠谱客的博主 壮观钢笔,最近开发中收集的这篇文章主要介绍【opencv初学者】11、RGB图像转NV21,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <vector>
#include <fstream>
#include <string>



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初学者】11、RGB图像转NV21的全部内容,希望文章能够帮你解决【opencv初学者】11、RGB图像转NV21所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部