bgfg.cpp 2.57 KB
Newer Older
1 2 3 4 5 6 7 8 9
#include "opencv2/bgsegm.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include <opencv2/core/utility.hpp>
#include <iostream>

using namespace cv;
using namespace cv::bgsegm;

10 11 12 13 14 15 16 17 18 19 20 21
const String about =
    "\nA program demonstrating the use and capabilities of different background subtraction algrorithms\n"
    "Using OpenCV version " + String(CV_VERSION) +
    "\nPress q or ESC to exit\n";

const String keys =
        "{help h usage ? |      | print this message   }"
        "{vid            |      | path to a video file }"
        "{algo           | GMG  | name of the algorithm (GMG, CNT, KNN, MOG, MOG2) }"
        ;

static Ptr<BackgroundSubtractor> createBGSubtractorByName(const String& algoName)
22
{
23 24 25 26 27 28 29 30 31 32 33 34 35
    Ptr<BackgroundSubtractor> algo;
    if(algoName == String("GMG"))
        algo = createBackgroundSubtractorGMG(20, 0.7);
    else if(algoName == String("CNT"))
        algo = createBackgroundSubtractorCNT();
    else if(algoName == String("KNN"))
        algo = createBackgroundSubtractorKNN();
    else if(algoName == String("MOG"))
        algo = createBackgroundSubtractorMOG();
    else if(algoName == String("MOG2"))
        algo = createBackgroundSubtractorMOG2();

    return algo;
36 37 38 39 40 41 42
}

int main(int argc, char** argv)
{
    setUseOptimized(true);
    setNumThreads(8);

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    CommandLineParser parser(argc, argv, keys);
    parser.about(about);
    parser.printMessage();
    if (parser.has("help"))
    {
        parser.printMessage();
        return 0;
    }

    String videoPath = parser.get<String>("vid");
    String algoName = parser.get<String>("algo");

    if (!parser.check())
    {
        parser.printErrors();
        return 0;
    }

    Ptr<BackgroundSubtractor> bgfs = createBGSubtractorByName(algoName);
    if (!bgfs)
63
    {
64
        std::cerr << "Failed to create " << algoName << " background subtractor" << std::endl;
65 66 67 68 69
        return -1;
    }

    VideoCapture cap;
    if (argc > 1)
70
        cap.open(videoPath);
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    else
        cap.open(0);

    if (!cap.isOpened())
    {
        std::cerr << "Cannot read video. Try moving video file to sample directory." << std::endl;
        return -1;
    }

    Mat frame, fgmask, segm;

    namedWindow("FG Segmentation", WINDOW_NORMAL);

    for (;;)
    {
        cap >> frame;

        if (frame.empty())
            break;

91
        bgfs->apply(frame, fgmask);
92 93 94 95 96 97 98 99 100 101 102 103 104

        frame.convertTo(segm, CV_8U, 0.5);
        add(frame, Scalar(100, 100, 0), segm, fgmask);

        imshow("FG Segmentation", segm);

        int c = waitKey(30);
        if (c == 'q' || c == 'Q' || (c & 255) == 27)
            break;
    }

    return 0;
}