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;
}

如果要把图片合成视频,代码也差不多,同样需要指定MJPG编码

#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()
{
	Mat image;
	char filename[1000]; //图片的名称
	int isColor = 1;     //如果为0 ,可输出灰度图像
	int fps = 10;        //设置输出视频的帧率
					   
	VideoWriter writer("video_out.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), fps,
		Size(360,240), isColor);

	for (unsigned int i = 1; i<=120; i++)
	{
        //我的图片名称是:0001.jpg, ..... 0120.jpg
		sprintf(filename, "E:/sequences/Crossing/img/0%03d.jpg", i);   
		image = imread(filename);//导入图片
		if (image.empty())
		{
			break;
		}
		waitKey(0);
		//cout << image.channels() << endl; //调试用
		//cout << image.size() << endl;     //调试用
		writer.write(image); 
	}
	writer.release();
	return 0;
}

 

posted @ 2018-10-06 13:33  SpaceVision  阅读(59)  评论(0编辑  收藏  举报