1. 程式人生 > >圖片儲存為YUV格式

圖片儲存為YUV格式

儲存為NV12格式的yuv420,yyyuvuvuv

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

int main()
{
	std::string jpgpath = "test.jpg";
	cv::Mat img = cv::imread(jpgpath);
	int w = img.cols;                 /* 寬 */
	int h = img.
rows; /* 高 */ int imageLength = h * w * 3 / 2; /* 影象y、u、v個數總和 */ unsigned char*yuv_nv12 = new unsigned char[imageLength]; /* 儲存nv12資料 */ unsigned char*yuv = new unsigned char[imageLength]; /* 儲存CV_BGR2YUV_I420資料 */ cv::cvtColor(img, img, CV_BGR2YUV_IYUV); /* BGR空間轉換為CV_BGR2YUV_I420 */
memcpy(yuv_nv12, img.data, imageLength*sizeof(unsigned char)); /* 此時yuv_nv12中儲存的是CV_BGR2YUV_I420型別資料 */ memcpy(yuv, img.data, imageLength*sizeof(unsigned char)); /* 此時yuv中儲存的是CV_BGR2YUV_I420型別資料 */ int num = 0; /* 對u、v個數的計數 */ for (int j = w * h; j != imageLength; j += 2) { yuv_nv12[j] = yuv[
w * h + num]; /* 對yuv_nv12中u分量進行賦值 */ yuv_nv12[j + 1] = yuv[w * h + w * h / 4 + num]; /* 對yuv_nv12中v分量進行賦值 */ ++num; } /* 儲存nv12格式的yuv420 */ FILE *fp = NULL; std::string outpath = "test.yuv"; fp = fopen(outpath.c_str(), "wb+"); if (!fp) { printf("file does not exist\n"); } fwrite(yuv_nv12, 1, sizeof(char)* imageLength, fp); fclose(fp); fp = NULL; /* 釋放記憶體 */ delete[]yuv_nv12; delete[]yuv; yuv_nv12 = nullptr; yuv = nullptr; system("pause"); }

儲存為CV_BGR2YUV_I420(YUV420)格式的yuv420,yyyuuuvvv

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

int main()
{
	std::string jpgpath = "test.jpg";
	cv::Mat img = cv::imread(jpgpath);
	int w = img.cols;
	int h = img.rows;
	int imageLength = h * w * 3 / 2;

	unsigned char*yuv = new unsigned char[imageLength];
	cv::cvtColor(img, img, CV_BGR2YUV_IYUV);
	memcpy(yuv, img.data, imageLength*sizeof(unsigned char));

	/* 儲存YUV420格式的yuv420 */
	FILE *fp = NULL;
	std::string outpath = "test.yuv";
	fp = fopen(outpath.c_str(), "wb+");
	if (!fp)
	{
		printf("file does not exist\n");
	}
	fwrite(yuv, 1, sizeof(char)* imageLength, fp);
	fclose(fp);
	fp = NULL;

	/* 釋放記憶體 */
	delete[]yuv;
	yuv = nullptr;

	system("pause");
}