Opencv: 将 YUV 格式的图片转化成 JPG 保存

        昨天刚和同事一起去采集一些场地数据,用板子拍摄然后实时传到电脑上,得到的是 NV21 的 YUV 格式的照片,然后暂时需要将他们批量处理成 jpg 的文件方便在 windows 上面看。参考同事的代码,写了一个 c++ 的脚本,简简单单的一个程序写了我半天,哎 c++ 的知识还是太不扎实。

#include 
#include 
#include 
#include 
#include 

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

using namespace std;
using namespace cv;

void GetAllFiles(string path, vector& files)
{
	intptr_t hFile = 0;
	struct _finddata_t fileinfo;
	string p;

	if ((hFile = _findfirst(p.assign(path).append("/*").c_str(), &fileinfo)) != -1)
	{
		do {
			if ((fileinfo.attrib != _A_SUBDIR))
			{
				files.push_back(p.assign(path).append("/").append(fileinfo.name));
				//cout << p.assign(path).append("/").append(fileinfo.name) << endl;
			}
		} while (_findnext(hFile, &fileinfo) == 0);

		_findclose(hFile);
	}
}

void YUV2JPG(string inputFileName, string savepath) 
{
	int iWidth, iHeight, iImageSize;
	iWidth = 1920;
	iHeight = 1056;
	iImageSize = iWidth * iHeight * 3 / 2;
	
	FILE * fpln;
	fpln = fopen(inputFileName.data(), "rb+");
	//cout << fpln << endl;
	if (fpln == NULL) {
		printf("read yuv error.\n");
	}

	cv::Mat yuvImg;
	cv::Mat rgbImg(iHeight, iWidth, CV_8UC3);
	yuvImg.create(iHeight * 3 / 2, iWidth, CV_8UC1);
	
	unsigned char *pYUVbuf = new unsigned char[iImageSize];
	fread(pYUVbuf, iImageSize * sizeof(unsigned char), 1, fpln);
	memcpy(yuvImg.data, pYUVbuf, iImageSize * sizeof(unsigned char));
	cv::cvtColor(yuvImg, rgbImg, CV_YUV2RGBA_NV21);

	imshow("test", rgbImg);
	waitKey(1000);

	imwrite(savepath, rgbImg);
}

int main() {
	string fp_front = "D:/GitFile/roadlane-detect-cpp/yuv/front/";
	string fp_rear = "D:/GitFile/roadlane-detect-cpp/yuv/rear";
	//cout << fp << endl;
	char sp_front[128], sp_rear[128];
	string Ipath;
	vector list1, list2;
	GetAllFiles(fp_front, list1);
	GetAllFiles(fp_rear, list2);
	for (int i = 0; i < list1.size(); i++)
	{
		sprintf(sp_front, "D:/GitFile/roadlane-detect-cpp/jpg/front/%d.jpg", i);
		YUV2JPG(list1.at(i), sp_front);
	}
	for (int i = 0; i < list2.size(); i++)
	{
		sprintf(sp_rear, "D:/GitFile/roadlane-detect-cpp/jpg/rear/%d.jpg", i);
		YUV2JPG(list2.at(i), sp_rear);
	}
	return 0;
}

 

你可能感兴趣的:(深度学习:CV和NLP)