Thanks berak - it is working now. Perfect. It creates the two videos of the mask and the other one, which are the trails?
For reference, the working code:
#include <iostream>
#include <sstream>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
using namespace cv;
using namespace std;
const char* params
= "{ help h | | Print usage }"
"{ input | vtest.avi | Path to a video or a sequence of image }"
"{ algo | MOG2 | Background subtraction method (KNN, MOG2) }";
int main(int argc, char* argv[])
{
CommandLineParser parser(argc, argv, params);
parser.about( "This program shows how to use background subtraction methods provided by "
" OpenCV. You can process both videos and images.\n" );
if (parser.has("help"))
{
//print help information
parser.printMessage();
return 0;
}
//create Background Subtractor objects
Ptr<BackgroundSubtractor> pBackSub;
if (parser.get<String>("algo") == "MOG2")
pBackSub = createBackgroundSubtractorMOG2(500, 16, false);
else
pBackSub = createBackgroundSubtractorKNN(500, 400.0, false);
VideoCapture capture( samples::findFile( parser.get<String>("input") ) );
//Initialize video writer object
// for saving
if (!capture.isOpened()){
//error in opening the video input
cerr << "Unable to open: " << parser.get<String>("input") << endl;
return 0;
}
int frame_width = static_cast<int>(capture.get(3));
int frame_height = static_cast<int>(capture.get(4));
Size frame_size(frame_width, frame_height);
int fps = 25;
VideoWriter foregroundmask("foregroundmask.avi",
VideoWriter::fourcc('M', 'J', 'P', 'G'),
fps,
frame_size,
false);
VideoWriter bgrmask("bgrmask.avi",
VideoWriter::fourcc('M', 'J', 'P', 'G'),
fps,
frame_size,
true);
Mat frame, fgMask;
Mat bgr_mask(frame.size(), CV_8UC3, Scalar::all(0));
while (true) {
capture >> frame;
if (frame.empty())
break;
//update the background model
pBackSub->apply(frame, fgMask, 0.8);
imshow("FG Mask", fgMask);
//foregroundmask
foregroundmask.write(fgMask);
//imshow("FG Mask", fgMask);
frame.copyTo(bgr_mask, fgMask);
//write background colour info to foregroundmask file
bgrmask.write(bgr_mask);
// imshow("colour", bgr_mask);
//get the input from the keyboard
int keyboard = waitKey(30);
if (keyboard == 'q' || keyboard == 27)
break;
}
// Release video writer foregroundmask
foregroundmask.release();
bgrmask.release();
return 0;
}