參考博文:http://blog.sina.com.cn/s/blog_60b330b801018s0u.html
運行環境:Win7 OpenCV1.0 VC6.0,下面生成視頻的代碼用到的是XVID編碼器,如果電腦上沒有需要下載,否則生成的視頻文件大小為0。或者將cvCreateVideoWriter("out.avi",CV_FOURCC('X','V','I','D'),fps,cvSize(frameW,frameH),isColor)的'X','V','I','D'修改為電腦上已有的編碼器即可。
注:是將多張圖像合並成視頻的,所以最後生成的視頻是沒有聲音的。
1 // 該程序實現視頻和圖片的相互轉換. 2 // Image_to_video()函數將一組圖片合成AVI視頻文件. 3 // Video_to_image()函數將AVI視頻文件讀入,將每一幀存儲為jpg文件. 4 // 5 //////////////////////////////////////////////////////////////////////// 6 #include <stdlib.h> 7 #include <stdio.h> 8 #include <math.h> 9 #include <cv.h> 10 #include <highgui.h> 11 #define NUM_FRAME 300 //只處理前300幀,根據視頻幀數可修改 12 13 void Video_to_image(char* filename) 14 { 15 printf("------------- video to image ... ----------------\n"); 16 //初始化一個視頻文件捕捉器 17 CvCapture* capture = cvCaptureFromAVI(filename); 18 //獲取視頻信息 19 cvQueryFrame(capture); 20 int frameH = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); 21 int frameW = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); 22 int fps = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS); 23 int numFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT); 24 printf("\tvideo height : %d\n\tvideo width : %d\n\tfps : %d\n\tframe numbers : %d\n", frameH, frameW, fps, numFrames); 25 //定義和初始化變量 26 int i = 0; 27 IplImage* img = 0; 28 char image_name[13]; 29 30 cvNamedWindow( "mainWin", CV_WINDOW_AUTOSIZE ); 31 //讀取和顯示 32 while(1) 33 { 34 35 img = cvQueryFrame(capture); //獲取一幀圖片 36 cvShowImage( "mainWin", img ); //將其顯示 37 char key = cvWaitKey(20); 38 39 sprintf(image_name, "%s%d%s", "image", ++i, ".jpg");//保存的圖片名 40 41 cvSaveImage( image_name, img); //保存一幀圖片 42 43 if(i == NUM_FRAME) break; 44 } 45 cvReleaseCapture(&capture); 46 cvDestroyWindow("mainWin"); 47 } 48 void Image_to_video() 49 { 50 int i = 0; 51 IplImage* img = 0; 52 char image_name[13]; 53 printf("------------- image to video ... ----------------\n"); 54 //初始化視頻編寫器,參數根據實際視頻文件修改 55 CvVideoWriter *writer = 0; 56 int isColor = 1; 57 int fps = 30; // or 25 58 int frameW = 400; // 744 for firewire cameras 59 int frameH = 240; // 480 for firewire cameras 60 writer=cvCreateVideoWriter("out.avi",CV_FOURCC('X','V','I','D'),fps,cvSize(frameW,frameH),isColor); 61 printf("\tvideo height : %d\n\tvideo width : %d\n\tfps : %d\n", frameH, frameW, fps); 62 //創建窗口 63 cvNamedWindow( "mainWin", CV_WINDOW_AUTOSIZE ); 64 while(i<NUM_FRAME) 65 { 66 sprintf(image_name, "%s%d%s", "image", ++i, ".jpg"); 67 img = cvLoadImage(image_name); 68 if(!img) 69 { 70 printf("Could not load image file...\n"); 71 exit(0); 72 } 73 cvShowImage("mainWin", img); 74 char key = cvWaitKey(20); 75 cvWriteFrame(writer, img); 76 } 77 cvReleaseVideoWriter(&writer); 78 cvDestroyWindow("mainWin"); 79 } 80 81 int main(int argc, char *argv[]) 82 { 83 char filename[13] = "infile.avi"; 84 Video_to_image(filename); //視頻轉圖片 85 Image_to_video(); //圖片轉視頻 86 return 0; 87 } 88 //--------------------------------------------------------------------------------