1. 程式人生 > >opencv+vs2017實現視訊的讀取及播放,同時將每一幀圖片儲存在指定檔案

opencv+vs2017實現視訊的讀取及播放,同時將每一幀圖片儲存在指定檔案


 
  
#include "highgui.h" 
#include <iostream> 
using namespace std; 


int main(int argc, char** argv) 
{
	cvNamedWindow("視訊播放器", CV_WINDOW_AUTOSIZE);
	//引數可以是裝置的索引號,或者是一個視訊檔案。裝置索引號就是在指定要使用的攝像頭。
	//一般的膝上型電腦都有內建攝像頭。所以引數就是 0。你可以通過設定成 1 或者其他的來選擇別的攝像頭。 
	// 用cvCaptureFromAVI()跟cvCaptureFromFile()、cvCreateFileCapture()都是一樣的作用 
	CvCapture* capture = cvCreateFileCapture(".\\video1.mp4"); //獲取視訊 
	IplImage* frame; 
	int i = 0; 
	char image_name[25]; 
	int pos = 0; 
	int pos1 = 0; 
	while (1) 
	{ 
		cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, pos); 
		cout << pos; frame = cvQueryFrame(capture); //獲取一幀圖片,將其顯示 
		pos1 = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES); 
		cout << "\t" << pos1 << endl; 
		if (!frame) break; 
		cvShowImage("視訊播放器", frame); //顯示每一幀 
		sprintf(image_name, "%s%.4d%s", ".\\tutu15\\", ++i, ".jpg");//儲存的圖片名 
		cvSaveImage(image_name, frame); //儲存一幀圖片 
		char c = cvWaitKey(33); 
		if (c == 27) break; 
		pos += 12; // 快進,每隔12幀顯示一幀圖片 
	} 
	cvReleaseCapture(&capture); 
	cvDestroyWindow("視訊播放器"); 
	system("pause"); 
}


讀取視訊並播放的另一種方法:

#include "stdafx.h"
#include <opencv2/core/core.hpp>    
#include <opencv2/highgui/highgui.hpp>    

using namespace cv;


void main()
{
	//VideoCapture capture(0);
	VideoCapture capture("video1.mp4");
	Mat frame;
	
	while (capture.isOpened())
	{
		capture >> frame;
                // capture.read(fram); //另一種獲取幀的方式
		imshow("video", frame);
		
		if (cvWaitKey(20) == 27)  //資料說明,在顯示影象的時候,每秒顯示27、28幀的時候,我們看到的視訊是流暢的
		{
			break;
		}
	}
	waitKey(0);
}

第三種方法:
using namespace cv;  

int main(int argc,char *argv[])  
{  
	VideoCapture cap(0);//開啟預設的攝像頭
	if(!cap.isOpened())  
	{  
		return -1;  
	}  
	Mat frame;  	
	bool stop = false;  
	while(!stop)  
	{  		
		cap.read(frame); //  或cap>>frame;			
		imshow("Video",frame);
		if(waitKey(30)==27) //Esc鍵退出
		{
			stop = true;  
		}  
	}
	return 0;  
}