因为要用到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;
}