码迷,mamicode.com
首页 > 其他好文 > 详细

avi视频格式转yuv格式与播放yuv视频

时间:2015-07-23 21:53:08      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:视频   编码   

由于要用到yuv格式视频,而目前只有avi格式的视频,所以需要转换,并且opencv不支持yuv编码的视频播放,所以需要转换为rgb编码,而后播放。写了两个程序,以供参考:

1,avi格式视频转yuv格式视频

2,播放并保存yuv视频

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>
void avi2WriteYuv(const char *in,const char *out)
{
	cv::VideoCapture vc;
	bool flag = vc.open(in);
	if (!flag)
	{
		printf("avi file open error \n");
		system("pause");
		exit(-1);
	}

	int frmCount = vc.get(CV_CAP_PROP_FRAME_COUNT);
	frmCount -= 5;
	printf("frmCount: %d \n", frmCount);

	int w = vc.get(CV_CAP_PROP_FRAME_WIDTH);
	int h = vc.get(CV_CAP_PROP_FRAME_HEIGHT);
	printf("wwwwww%d\n", w);
	printf("hhhhhh%d\n", h);
	int bufLen = w*h * 3 / 2;
	unsigned char* pYuvBuf = new unsigned char[bufLen];
	FILE* pFileOut = fopen(out, "w+");
	if (!pFileOut)
	{
		printf("pFileOut open error \n");
		system("pause");
		exit(-1);
	}
	printf("pFileOut open ok \n");

	for (int i = 0; i<frmCount; i++)
	{
		printf("%d/%d \n", i + 1, frmCount);

		cv::Mat srcImg;
		vc >> srcImg;

		cv::imshow("img", srcImg);
		cv::waitKey(1);

		cv::Mat yuvImg;
		cv::cvtColor(srcImg, yuvImg, CV_BGR2YUV_I420);
		memcpy(pYuvBuf, yuvImg.data, bufLen*sizeof(unsigned char));

		fwrite(pYuvBuf, bufLen*sizeof(unsigned char), 1, pFileOut);
	}

	fclose(pFileOut);
	delete[] pYuvBuf;
}
void DisplayYUV2RGB(const char *dir,const char *in,int _w,int _h)
{
	int w = _w;
	int h = _h;
	printf("yuv file w: %d, h: %d \n", w, h);

	FILE* pFileIn = fopen(in, "rb+");
	int bufLen = w*h * 3 / 2;
	unsigned char* pYuvBuf = new unsigned char[bufLen];
	int iCount = 0;


	for (int i = 0; i<95; i++)
	{
		fread(pYuvBuf, bufLen*sizeof(unsigned char), 1, pFileIn);

		cv::Mat yuvImg;
		yuvImg.create(h * 3 / 2, w, CV_8UC1);
		memcpy(yuvImg.data, pYuvBuf, bufLen*sizeof(unsigned char));
		cv::Mat rgbImg;
		cv::cvtColor(yuvImg, rgbImg, CV_YUV2BGR_I420);

		cv::imshow("img", rgbImg);
		char s[100];
		sprintf(s,"%spic%d%s",dir,i,".jpg");
		cv::imwrite(s, rgbImg);
		cv::waitKey(1);

		printf("%d \n", iCount++);
	}

	delete[] pYuvBuf;


	fclose(pFileIn);
}

int main(int argc, char *argv[])
{
	const char *in = "C:/Users/jiang/Desktop/output/outfile.avi";
	const char *out = "C:/Users/jiang/Desktop/output/outfile.yuv";
	const char *dir = "C:/Users/jiang/Desktop/output/tupian1/";
	avi2WriteYuv(in,out);
	DisplayYUVtoRGB(dir,out, 1024, 768);
	return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

avi视频格式转yuv格式与播放yuv视频

标签:视频   编码   

原文地址:http://blog.csdn.net/u012361418/article/details/47028133

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!