opencv显示yuv420,YV12视频文件

来源:互联网 发布:windows 3.0 编辑:程序博客网 时间:2024/06/05 07:03



#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp>#include <iostream>#include <fstream>#include <boost/filesystem.hpp>#include <boost/thread.hpp>#include "generalImgFun.hpp"#include <math.h> using namespace std; using namespace cv; void WriteYuv() {     cv::VideoCapture vc;     bool flag = vc.open("S1000008.avi");     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);     int bufLen = w*h*3/2;     unsigned char* pYuvBuf = new unsigned char[bufLen];     FILE* pFileOut = fopen("result.yuv", "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 DisplayYUV(int w,int h , int fps ,string yuv_file_path) {     printf("yuv file w: %d, h: %d \n", w, h);     FILE* pFileIn = fopen(yuv_file_path.c_str(), "rb+"); fseek(pFileIn, 0, SEEK_END); int frame_count = 0; frame_count = (int) ((int)ftell(pFileIn)/((w * h * 3) / 2));  // ftell 用于求文件大小 printf("frame num is %d \n", frame_count); fseek(pFileIn, 0, SEEK_SET);//文件内位置定位到文件头     int bufLen = w*h*3/2;     unsigned char* pYuvBuf = new unsigned char[bufLen];     for(int i=0; i<frame_count; 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("yuv", yuvImg);         cv::imshow("rgb", rgbImg);         cv::waitKey(1000/fps);         printf("cnt: %d \n", i);     }     delete[] pYuvBuf;     fclose(pFileIn); }int main(int argc, char** argv){if(argc<4){cout<<"usage: ./yuv_checker yuv_file.yuv width height fps!"<<endl;exit(1);}stringstream ss; ss <<argv[2];int nWidth ;int nHeight;int fps ;ss >> nWidth ;ss.clear(); ss<<argv[3];ss >> nHeight ;ss.clear(); ss<<argv[4];ss >> fps ;cout <<" width:"<<argv[2]<<" height:"<<argv[3]<<" fps:"<<argv[4]<<" file:"<<argv[1]<<endl;DisplayYUV(nWidth,nHeight,fps,argv[1]);return 0;}




3 0
原创粉丝点击