Opencv保存视频

时间:2017-06-10 13:30:43

标签: c++ opencv video

我正在使用级联检测对象,我想在检测后保存我的视频但是我只能保存一帧(我可以只保存最后一帧) 我的代码在这里:

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp> 
#include <iostream>
#include <stdio.h>
#include <opencv2/objdetect/objdetect.hpp>
using namespace std;
using namespace cv;
int main()
{
CascadeClassifier nesne;
nesne.load("cascade.xml");
string filename = "a.avi";
    VideoCapture capture(filename);

Mat frame;
Mat grires;
namedWindow("algilanan", 1);

while(true)
{
capture>>frame;
cvtColor(frame, grires, CV_BGR2GRAY);  //resmi gri renk uzayına çevirir. 
vector<Rect> nesvek;
nesne.detectMultiScale(grires, nesvek, 1.1, 3, 0, Size(30,30));
for(int i = 0; i < nesvek.size(); i++)
{
Point pt1(nesvek[i].x + nesvek[i].width, nesvek[i].y + nesvek[i].height);
Point pt2(nesvek[i].x, nesvek[i].y);
rectangle(frame, pt1, pt2, cvScalar(0, 255, 0, 0), 1, 8, 0);

}
int frame_width=   capture.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height=   capture.get(CV_CAP_PROP_FRAME_HEIGHT);
VideoWriter video("out.avi",CV_FOURCC('M','J','P','G'),10, Size(frame_width,frame_height),true);
video.write(frame);
imshow("algilanan", frame);
waitKey(33);

}
return 0;
}

1 个答案:

答案 0 :(得分:4)

您可以保存单个帧的原因是因为您在循环的每次迭代中重新初始化VideoWriter。你应该在循环之外初始化它。试试这个。

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp> 
#include <iostream>
#include <stdio.h>
#include <opencv2/objdetect/objdetect.hpp>
using namespace std;
using namespace cv;
int main()
{
CascadeClassifier nesne;
nesne.load("cascade.xml");
string filename = "a.avi";
VideoCapture capture(filename);

Mat frame;
Mat grires;
namedWindow("algilanan", 1);

int frame_width=   capture.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height=  capture.get(CV_CAP_PROP_FRAME_HEIGHT);
VideoWriter video("out.avi",CV_FOURCC('M','J','P','G'),10,Size(frame_width,frame_height),true);

while(true)
{
capture>>frame;
cvtColor(frame, grires, CV_BGR2GRAY);  //resmi gri renk uzayına çevirir. 
vector<Rect> nesvek;
nesne.detectMultiScale(grires, nesvek, 1.1, 3, 0, Size(30,30));
for(int i = 0; i < nesvek.size(); i++)
{
Point pt1(nesvek[i].x + nesvek[i].width, nesvek[i].y + nesvek[i].height);
Point pt2(nesvek[i].x, nesvek[i].y);
rectangle(frame, pt1, pt2, cvScalar(0, 255, 0, 0), 1, 8, 0);
}  
video.write(frame);
imshow("algilanan", frame);
waitKey(33);

}
return 0;
}