1. 程式人生 > >OpenCV視訊播放操作

OpenCV視訊播放操作

使用VideoCapture類實現視訊播放:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
	VideoCapture video;
	video.open("test.mp4");  //開啟視訊
	if (!video.isOpened()) 
	{
		cout << "open video failed!" << endl;
		getchar();
		return -1;
	}
	cout << "open video success!" << endl;
	namedWindow("video");
	Mat frame;
	int fps = video.get(CAP_PROP_FPS);  //獲取幀率
	int s = 30;
	if (fps != 0)
		s = 1000 / fps;
	cout << "fps is " << fps << endl;
	int fcount = video.get(CAP_PROP_FRAME_COUNT);  //獲取總幀數
	cout << "total frame is " << fcount << endl;
	cout << "total sec is " << fcount / fps << endl;  //計算視訊時間
	//獲取幀寬
	cout << "CAP_PROP_FRAME_WIDTH " << video.get(CAP_PROP_FRAME_WIDTH) << endl;

	s = s / 2;  //視訊播放加速一倍

	//視訊播放
	for (;;)
	{
		video.read(frame);
		if (frame.empty()) break;
		int cur = video.get(CAP_PROP_POS_FRAMES);  //獲取當前播放幀數
		//迴圈播放
		if (cur > fcount-1)
		{
			video.set(CAP_PROP_POS_FRAMES, 0);  //設定播放位置
			continue;
		}
		imshow("video", frame);
		waitKey(s);
	}
	getchar();
	return 0;
}