1. 程式人生 > >OpenCV3.1錄製視訊(OpenCV不能開啟自己錄製的視訊)

OpenCV3.1錄製視訊(OpenCV不能開啟自己錄製的視訊)

記一下,備忘。

用OpenCV開啟OpenCV錄製的視訊,發現報錯,程式碼如下

	cv::VideoCapture capture;
	capture.open("E:\\opencv.avi");

追蹤了一下,原來是開啟要求用MJPG,


bool AviMjpegStream::parseStrl(MjpegInputStream& in_str, uint8_t stream_id)
{
...
========> 這裡要求是MJPG_CC
        if(strm_hdr.fccType == VIDS_CC && strm_hdr.fccHandler == MJPG_CC) 
        {...
        }
...
}

所以錄製時把屬性設定為 VideoWriter::fourcc('M', 'J', 'P', 'G')即可,下面是錄製視訊的原碼,

#include "stdafx.h"

#include<opencv2/opencv.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<opencv2\core\core.hpp>
using namespace cv;

#pragma comment(lib, "opencv_world310d.lib")

#include<iostream>
using namespace std;


int main()
{
	//開啟攝像頭
	VideoCapture captrue(0);
	//視訊寫入物件
	VideoWriter write;
	//寫入視訊檔名
	string outFlie = "E://opencv.avi";
	//獲得幀的寬高
	int w = static_cast<int>(captrue.get(CV_CAP_PROP_FRAME_WIDTH));
	int h = static_cast<int>(captrue.get(CV_CAP_PROP_FRAME_HEIGHT));
	Size S(w, h);
	//獲得幀率
	captrue.set(CV_CAP_PROP_FPS, 25);
	double fps = captrue.get(CV_CAP_PROP_FPS);
	//開啟視訊檔案,準備寫入
	//write.open(outFlie, -1, r, S, true);
	//write.open(outFlie, CV_FOURCC('M', 'J', 'P', 'G'), fps, S, true); // this is OK too
	int val = VideoWriter::fourcc('M', 'J', 'P', 'G');
	write.open(outFlie, val, fps, S, true);
	//開啟失敗
	if (!captrue.isOpened())
	{
		return 1;
	}
	bool stop = false;
	Mat frame;
	//迴圈
	while (!stop)
	{
		//讀取幀
		if (!captrue.read(frame))
			break;
		imshow("Video", frame);
		//寫入檔案
		write.write(frame);
		if (waitKey(10) > 0)
		{
			stop = true;
		}
	}
	//釋放物件
	captrue.release();
	write.release();
	cvDestroyWindow("Video");
	return 0;
}