Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background and foreground in OpencV

Tags:

c++

c

opencv

i'm working on a project using OpenCV243, I need to get the foreground during a stream, my Problem is that I use the cv::absdiff to get it doesn't really help, here is my code and the result .

#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;
}

Background foreground as you can see the subtraction work but what I want to get is only the values of that changed for example if have a Pixel in the background with [130,130,130] and the same pixel has [200,200,200] in the frame I want to get exactly the last values and not [70,70,70] I've already seen this tutorial : http://mateuszstankiewicz.eu/?p=189 but I can't understand the code and I have problems setting cv::BackgroundSubtractorMOG2 with my openCV version

thanks in advance for you help

like image 644
Engine Avatar asked May 29 '13 08:05

Engine


1 Answers

BackgroundSubtractorMOG2 should work with #include "opencv2/video/background_segm.hpp" The samples with OpenCV have two nice c++ examples (in the samples\cpp directory).

  • bgfg_segm.cpp shows how to use the BackgroundSubtractorMOG2
  • bgfg_gmg.cpp uses BackgroundSubtractorGMG

To get the last values (and asuming you meant to get the foreground pixel values) you could copy the frame using the foreground mask. This is also done in the first example, in the following snippet:

bg_model(img, fgmask, update_bg_model ? -1 : 0);
fgimg = Scalar::all(0);
img.copyTo(fgimg, fgmask);
like image 194
ruben.k Avatar answered Oct 10 '22 21:10

ruben.k