背景和前景在OpencV

Eng*_*ine 6 c c++ opencv

我正在使用OpenCV243开发项目,我需要在流中获取前景,我的问题是我使用cv :: absdiff来获得它并没有真正帮助,这是我的代码和结果.

#include <iostream>
#include<opencv2\opencv.hpp>
#include<opencv2\calib3d\calib3d.hpp>
#include<opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>

int main (){
    cv::VideoCapture cap(0);
    cv::Mat frame,frame1,frame2;
    cap >> frame;
    frame.copyTo(frame1);
    cv::imwrite("background.jpeg",frame1);
    int key = 0;
    while(key!=27){
        cap >> frame;
        cv::absdiff(frame, frame1, frame2);  // frame2 = frame  -frame1
        cv::imshow("foreground", frame2);
        if(key=='c'){
            //frame.copyTo(frame2);
            cv::imwrite("foreground.jpeg", frame2); 
            key = 0;
        }

        cv::imshow("frame",frame);
        key = cv::waitKey(10);
    }
    cap.release();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

背景 前景 正如你可以看到减法工作,但我想要得到的只是更改的值,例如,如果在[130,130,130]的背景中有一个像素, 并且相同的像素 在帧中有[200,200,200]我想要得到的确切的最后的值,而不是[70,70,70] 我已经看过这个教程:http://mateuszstankiewicz.eu/?p = 189, 但我无法理解代码,我有问题设置cv :: BackgroundSubtractorMOG2与我openCV版本

在此先感谢您的帮助

小智 3

BackgroundSubtractorMOG2 应该可以使用#include "opencv2/video/background_segm.hpp" OpenCV 的示例有两个很好的 c++ 示例(在示例\cpp 目录中)。

  • bgfg_segm.cpp 展示了如何使用BackgroundSubtractorMOG2
  • bgfg_gmg.cpp 使用BackgroundSubtractorGMG

要获取最后的值(假设您打算获取前景像素值),您可以使用前景蒙版复制帧。这也在第一个示例中完成,如下代码片段:

bg_model(img, fgmask, update_bg_model ? -1 : 0);
fgimg = Scalar::all(0);
img.copyTo(fgimg, fgmask);
Run Code Online (Sandbox Code Playgroud)