I'm trying to play with my webcam and OpenCV. I follow this tuto : http://mateuszstankiewicz.eu/?p=189 . But the only result I have is one red border and I don't understand why. Could anyone help me to make it right and fix this ?
Here is my code :
#include "mvt_detection.h"
Mvt_detection::Mvt_detection()
{
}
Mvt_detection::~Mvt_detection()
{
}
cv::Mat Mvt_detection::start(cv::Mat frame)
{
cv::Mat back;
cv::Mat fore;
cv::BackgroundSubtractorMOG2 bg(5,3,true) ;
cv::namedWindow("Background");
std::vector<std::vector<cv::Point> > contours;
bg.operator ()(frame,fore);
bg.getBackgroundImage(back);
cv::erode(fore,fore,cv::Mat());
cv::dilate(fore,fore,cv::Mat());
cv::findContours(fore,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
cv::drawContours(frame,contours,-1,cv::Scalar(0,0,255),2);
return frame;
}
Here is a screenshot of what our cam returns :
I tried on two other video from there and there and there is the same issue.
Thanks for the help :).
I have used the following code which is similar to yours and it is working well. I am also taking the inputs from my webcam. In your code, i didnt find any imshow() and waitkey. Try to use them. My code is following:
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
int main()
{
VideoCapture cap;
bool update_bg_model = true;
cap.open(0);
cv::BackgroundSubtractorMOG2 bg;//(100, 3, 0.3, 5);
bg.set ("nmixtures", 3);
std::vector < std::vector < cv::Point > >contours;
cv::namedWindow ("Frame");
cv::namedWindow ("Background");
Mat frame, fgmask, fgimg, backgroundImage;
for(;;)
{
cap >> frame;
bg.operator()(frame, fgimg);
bg.getBackgroundImage (backgroundImage);
cv::erode (fgimg, fgimg, cv::Mat ());
cv::dilate (fgimg, fgimg, cv::Mat ());
cv::findContours (fgimg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::drawContours (frame, contours, -1, cv::Scalar (0, 0, 255), 2);
cv::imshow ("Frame", frame);
cv::imshow ("Background", backgroundImage);
char k = (char)waitKey(30);
if( k == 27 ) break;
}
return 0;
}
解决了问题,将BackgroundSubtractorMOG2放在我的对象的字段中并在构造函数中对其进行初始化使他可以正常工作。
As @Lenjyco said, we fixe the problem.
@Micka had a good idea :
Firstly the BackgroundSubtractorMOG2 as to be instancied only ONCE.
We instantiate it in the constructor and play with the Hystory and Threashold:
Mvt_detection::Mvt_detection()
{
bg = new cv::BackgroundSubtractorMOG2(10, 16, false);
}
10 : the number of image the backgound look back to compare.
16 : the threshold level (blur)
This way, we are now able to detect motion.
Thank you !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.