本文主要是介绍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_CCif(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 tooint 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.jpgsprintf(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;
}
这篇关于OpenCV3.1录制视频+把图片合成视频(同时解决一个OpenCV不能打开自己录制的视频的小问题)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!