[英]Video capture and save using OpenCV
下面给出的是我用于从网络摄像头获取视频并将其保存在硬盘上的代码。 运行该程序时,显示“视频编写器未打开”。 我要去哪里错了?
#include <opencv\cv.h>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
#define default_buflen 1024
using namespace std;
using namespace cv;
#define default_port "1234"
int main(int argc, char** argv)
{
Mat capture;
VideoCapture cap(0);
if(!cap.isOpened())
{
cout<<"Cannot connect to camera"<<endl;
getchar();
return -1;
}
double fps=30;
Size s=Size((int)cap.get(CV_CAP_PROP_FRAME_WIDTH),(int)cap.get(CV_CAP_PROP_FRAME_WIDTH));
VideoWriter vidcapt;
vidcapt.open("c:\\out.avi",CV_FOURCC('D','I','V','X'),cap.get(CV_CAP_PROP_FPS),s,true);
if(!vidcapt.isOpened())
{
cout<<"Video writer not opening"<<endl;
getchar();
return -1;
}
while(true)
{
cap>>capture;
namedWindow("Display",1);
imshow("Display",capture);
vidcapt<<capture;
int ch=waitKey(5);
if(char(ch)==27)
{
break;
}
}
}
尝试其他编解码器
CV_FOURCC('P','I','M','1')= MPEG-1编解码器
CV_FOURCC('M','J','P','G')= motion-jpeg编解码器(效果不佳)
CV_FOURCC('M','P','4','2')= MPEG-4.2编解码器
CV_FOURCC('D','I','V','3')= MPEG-4.3编解码器
CV_FOURCC('D','I','V','X')= MPEG-4编解码器
CV_FOURCC('U','2','6','3')= H263编解码器
CV_FOURCC('I','2','6','3')= H263I编解码器
CV_FOURCC('F','L','V','1')= FLV1编解码器
复制从这里粘贴。 我设法用CV_FOURCC('F','L','V','1')编写视频。
顺便说一句,当然应该在您的计算机上安装编解码器。
根据您的代码,我无法理解为什么在while循环中每次创建窗口Display
原因,而且每次可能出错时都要初始化VideoWriter
对象。 我对您的代码做了一些修改,如下所示,请尝试,它可能对您有帮助
#include <opencv\cv.h>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
#define default_buflen 1024
using namespace std;
using namespace cv;
#define default_port "1234"
int main(int argc, char** argv)
{
Mat capture;
VideoCapture cap(0);
if(!cap.isOpened())
{
cout<<"Cannot connect to camera"<<endl;
getchar();
return -1;
}
namedWindow("Display",CV_WINDOW_AUTOSIZE);
double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);
double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
Size frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));
VideoWriter oVideoWriter ("c:\\out.avi", CV_FOURCC('P','I','M','1'), 20, frameSize,true);
if ( !oVideoWriter.isOpened() )
{
cout << "ERROR: Failed to write the video" << endl;
return -1;
}
while(true)
{
Mat frame;
bool bSuccess = cap.read(frame); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "ERROR: Cannot read a frame from video file" << endl;
break;
}
oVideoWriter.write(frame); //writer the frame into the file
imshow("Display", frame);
if (waitKey(10) == 27)
{
cout << "esc key is pressed by user" << endl;
break;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.