5/12/2014

(OpenCV) Hue Histogram drawing and get value of RGB and bin count (example source code using calcHist in openCV)

This histogram drawing source code is referenced Sample code of CAMshift in opencv.

We usually use hue color in hsv to get color distribution, because hue is a little bit free from lighting than RGB model.

The source code is example of drawing rgb graph from hue histogram.

I try to drawing color graph from 2 channel histogram, for example hue, saturation, but I failed, I don't know that is impossible or not.

But 1 channel is possible, refer to this source code and fiagure.

If you want to know how to get histogram, refer to this page.
http://feelmare.blogspot.kr/2014/05/open-cv-get-histogram-and-compare-color.html

Thank you.

-----
#include <  stdio.h>
#include <  iostream>
#include <  opencv2\opencv.hpp>


#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing
#pragma comment(lib, "opencv_highgui247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#endif 

using namespace cv;
using namespace std;


//get representative 3 color

int main()
{
 
 //read 2 images for histogram comparing
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 Mat imgA;
 Mat imgA_mask;
 imgA = imread(".\\image1.jpg");
 imgA_mask = imread(".\\image1_mask.jpg", 0);

 imshow("img1", imgA);
 imshow("img1_mask", imgA_mask);


 //variables preparing
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 int hbins = 30; 
 int channels[] = {0};
 int histSize[] = {hbins};
 float hranges[] = { 0, 180 };
 const float* ranges[] = { hranges}; 

 Mat patch_HSV;
 MatND HistA, HistB;

 //cal histogram & normalization
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 cvtColor(imgA, patch_HSV, CV_BGR2HSV);
 calcHist( &patch_HSV, 1, channels,  imgA_mask, //MaskForHisto, // // do use mask
     HistA, 1, histSize, ranges,
     true, // the histogram is uniform
     false );
 normalize(HistA, HistA,  0, 255, CV_MINMAX);

 
 
 //Mat for drawing 
 Mat histimg = Mat::zeros(200, 320, CV_8UC3); 
 histimg = Scalar::all(0);
 int binW = histimg.cols / hbins;
 Mat buf(1, hbins, CV_8UC3);
 //Set RGB color
 for( int i = 0; i <  hbins; i++ )
  buf.at< Vec3b>(i) = Vec3b(saturate_cast< uchar>(i*180./hbins), 255, 255);
 cvtColor(buf, buf, CV_HSV2BGR);
 //drawing routine
 for( int i = 0; i <  hbins; i++ )
 {
  int val = saturate_cast< int>(HistA.at< float>(i)*histimg.rows/255);
  
  rectangle( histimg, Point(i*binW,histimg.rows),
   Point((i+1)*binW,histimg.rows - val),
   Scalar(buf.at< Vec3b>(i)), -1, 8 );
  int r,g,b;
  b =  buf.at< Vec3b>(i)[0];
  g =  buf.at< Vec3b>(i)[1];
  r =  buf.at< Vec3b>(i)[2];

  //show bin and RGB value
  printf("[%d] r=%d, g=%d, b=%d , bins = %d \n",i , r, g, b, val);
 }
 imshow( "Histogram", histimg );



 waitKey(0);

 return 0;
}


----

(opencv) get histogram and compare color similarity of 2 images(calcHist, compareHist, example source code)

This is example source code of get Histogram and compare color similarity of 2 images.

To get histogram, we use calcHist function in opencv and use compareHist to comparing.

Generally, when comparing based color, HSV color medel is more accurate then RGB model.

And using 2 channel of Hue, Saturation is better than using only 1 channel. ex) hue

In calcHist parameters, there is mask option. The mask image is black and white image.

When set mask option, calcHist get histogram only white region pixels. So if you knwo foreground of image, comparing value will be better.

First source code is no mask option.
Second source code is mask option.





#include <  stdio.h>
#include <  iostream>
#include <  opencv2\opencv.hpp>

#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing
#pragma comment(lib, "opencv_highgui247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#endif 

using namespace cv;
using namespace std;



int main()
{
 
 //read 2 images for histogram comparing
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 Mat imgA, imgB;
 imgA = imread(".\\image1.jpg");
 imgB = imread(".\\image2.jpg");

 
 imshow("img1", imgA);
 imshow("img2", imgB);


 //variables preparing
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 int hbins = 30, sbins = 32; 
 int channels[] = {0,  1};
 int histSize[] = {hbins, sbins};
 float hranges[] = { 0, 180 };
 float sranges[] = { 0, 255 };
 const float* ranges[] = { hranges, sranges}; 

 Mat patch_HSV;
 MatND HistA, HistB;

 //cal histogram & normalization
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 cvtColor(imgA, patch_HSV, CV_BGR2HSV);
 calcHist( &patch_HSV, 1, channels,  Mat(), // do not use mask
     HistA, 2, histSize, ranges,
     true, // the histogram is uniform
     false );
 normalize(HistA, HistA,  0, 255, CV_MINMAX);


 cvtColor(imgB, patch_HSV, CV_BGR2HSV);
 calcHist( &patch_HSV, 1, channels,  Mat(),// do not use mask
     HistB, 2, histSize, ranges,
     true, // the histogram is uniform
     false );
 normalize(HistB, HistB, 0, 255, CV_MINMAX);
 
 
 
 
 //compare histogram
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //λΉ„κ΅ν•˜κΈ°
 float bc = compareHist(HistA, HistB, CV_COMP_BHATTACHARYYA); 
 printf("(The range of matcing value is 0~1, 1 is best matching, 0 means miss matching\n");
 printf("V = %lf \n", bc);


 waitKey(0);

 return 0;
}



 
 

#include <  stdio.h>
#include <  iostream>
#include <  opencv2\opencv.hpp>

#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing
#pragma comment(lib, "opencv_highgui247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#endif 

using namespace cv;
using namespace std;



int main()
{
 
 //read 2 images for histogram comparing
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 Mat imgA, imgB;
 Mat imgA_mask, imgB_mask;
 imgA = imread(".\\image1.jpg");
 imgB = imread(".\\image2.jpg");
 imgA_mask = imread(".\\image1_mask.jpg", 0);
 imgB_mask = imread(".\\image2_mask.jpg", 0);
 
 imshow("img1", imgA);
 imshow("img2", imgB);
 imshow("img1_mask", imgA_mask);
 imshow("img2_mask", imgB_mask);


 //variables preparing
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 int hbins = 30, sbins = 32; 
 int channels[] = {0,  1};
 int histSize[] = {hbins, sbins};
 float hranges[] = { 0, 180 };
 float sranges[] = { 0, 255 };
 const float* ranges[] = { hranges, sranges}; 

 Mat patch_HSV;
 MatND HistA, HistB;

 //cal histogram & normalization
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 cvtColor(imgA, patch_HSV, CV_BGR2HSV);
 calcHist( &patch_HSV, 1, channels,  imgA_mask, //MaskForHisto, // // do use mask
     HistA, 2, histSize, ranges,
     true, // the histogram is uniform
     false );
 normalize(HistA, HistA,  0, 255, CV_MINMAX);


 cvtColor(imgB, patch_HSV, CV_BGR2HSV);
 calcHist( &patch_HSV, 1, channels,  imgB_mask, //MaskForHisto, // // do use mask
     HistB, 2, histSize, ranges,
     true, // the histogram is uniform
     false );
 normalize(HistB, HistB, 0, 255, CV_MINMAX);
 
 
 
 
 //compare histogram
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //λΉ„κ΅ν•˜κΈ°
 float bc = compareHist(HistA, HistB, CV_COMP_BHATTACHARYYA); 
 printf("(The range of matcing value is 0~1, 1 is best matching, 0 means miss matching\n");
 printf("V = %lf \n", bc);


 waitKey(0);

 return 0;
}

5/01/2014

(OpenCV Study) setMouseCallback function example source code, get rectangle coordinate of mouse drag on image.

This  source code is useful when you need retangle coordinate of mouse drag.
The rectangle coordinate is applied initial region for tracking.

refer to video and source code.

#include < stdio.h>
#include < iostream>

#include < opencv2\opencv.hpp>
//#include < opencv2/core/core.hpp>
//#include < opencv2/highgui/highgui.hpp>
//#include < opencv2/video/background_segm.hpp>
//#include < opencv2\gpu\gpu.hpp>
//#include < opencv2\legacy\legacy.hpp>

#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")
//#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing
//#pragma comment(lib, "opencv_objdetect247d.lib") //HOGDescriptor
//#pragma comment(lib, "opencv_gpu247d.lib")
//#pragma comment(lib, "opencv_features2d247d.lib")
#pragma comment(lib, "opencv_highgui247d.lib")
//#pragma comment(lib, "opencv_ml247d.lib")
//#pragma comment(lib, "opencv_stitching247d.lib");
//#pragma comment(lib, "opencv_nonfree247d.lib");
//#pragma comment(lib, "opencv_video247d.lib")
//#pragma comment(lib, "opencv_legacy247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
//#pragma comment(lib, "opencv_imgproc247.lib")
//#pragma comment(lib, "opencv_objdetect247.lib")
//#pragma comment(lib, "opencv_gpu247.lib")
//#pragma comment(lib, "opencv_features2d247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
//#pragma comment(lib, "opencv_ml247.lib")
//#pragma comment(lib, "opencv_stitching247.lib");
//#pragma comment(lib, "opencv_nonfree247.lib");
//#pragma comment(lib, "opencv_video247.lib")
//#pragma comment(lib, "opencv_legacy247.lib")
#endif 

using namespace std;
using namespace cv;

bool selectObject = false;
Rect selection;
Point origin;
int trackObject = 0;
Mat image;


static void onMouse( int event, int x, int y, int, void* )
{
    if( selectObject )
    {
        selection.x = MIN(x, origin.x);
        selection.y = MIN(y, origin.y);
        selection.width = std::abs(x - origin.x);
        selection.height = std::abs(y - origin.y);

        selection &= Rect(0, 0, image.cols, image.rows);
    }

    switch( event )
    {
    case CV_EVENT_LBUTTONDOWN:
        origin = Point(x,y);
        selection = Rect(x,y,0,0);
        selectObject = true;
        break;
    case CV_EVENT_LBUTTONUP:
        selectObject = false;
        if( selection.width > 0 && selection.height > 0 )
            trackObject = -1;
        break;
    }
}


int main (void)  
{  
 

 VideoCapture cap(0);
 Mat frame;
 namedWindow( "Demo", 0 );
 setMouseCallback( "Demo", onMouse, 0 );

    for(;;)
    {
        
  cap >> frame;
        if( frame.empty() )
   break;

        frame.copyTo(image);
  

  if( selectObject && selection.width > 0 && selection.height > 0 )
        {
            Mat roi(image, selection);
            bitwise_not(roi, roi);
   printf("%d %d %d %d\n", selection.x, selection.y, selection.width, selection.height);
        }

  imshow( "Demo", image );

  if( waitKey(10) > 10 )
   break;
 }

 return 0;  
}  



4/28/2014

(OpenCV Study) the example source code for using FarnebackOpticalFlow function (dense opticlal flow, gpu function)

This is GPU version of this post.
http://feelmare.blogspot.kr/2014/04/opencv-study-calcopticalflowfarneback.html

In the GPU mode, the return value of the function is two vector direction, that is x direction and y direction.
In the GPU mode, functions of resize, cvtColor cannot copy to same variable of gpumat.
And gputmat cannot access to the pixel point using at(x,y).


GPU is more fast about 10 times than cpu mode in my computer environment.

refer to this example source code and video.




#include < stdio.h>
#include < iostream>

#include < opencv2\opencv.hpp>
#include < opencv2/core/core.hpp>
#include < opencv2/highgui/highgui.hpp>
#include < opencv2/video/background_segm.hpp>
#include < opencv2\gpu\gpu.hpp>

#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing
#pragma comment(lib, "opencv_objdetect247d.lib") //HOGDescriptor
#pragma comment(lib, "opencv_gpu247d.lib")
//#pragma comment(lib, "opencv_features2d247d.lib")
#pragma comment(lib, "opencv_highgui247d.lib")
#pragma comment(lib, "opencv_ml247d.lib")
//#pragma comment(lib, "opencv_stitching247d.lib");
//#pragma comment(lib, "opencv_nonfree247d.lib");
#pragma comment(lib, "opencv_video247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_objdetect247.lib")
#pragma comment(lib, "opencv_gpu247.lib")
//#pragma comment(lib, "opencv_features2d247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#pragma comment(lib, "opencv_ml247.lib")
//#pragma comment(lib, "opencv_stitching247.lib");
//#pragma comment(lib, "opencv_nonfree247.lib");
#pragma comment(lib, "opencv_video247d.lib")
#endif 

using namespace cv;
using namespace std;


void drawOptFlowMap_gpu (const Mat& flow_x, const Mat& flow_y, Mat& cflowmap, int step, const Scalar& color) {

 

 for(int y = 0; y < cflowmap.rows; y += step)
        for(int x = 0; x < cflowmap.cols; x += step)
        {
   Point2f fxy; 
   fxy.x = cvRound( flow_x.at< float >(y, x) + x );
   fxy.y = cvRound( flow_y.at< float >(y, x) + y );
   
   line(cflowmap, Point(x,y), Point(fxy.x, fxy.y), color);
   circle(cflowmap, Point(fxy.x, fxy.y), 1, color, -1);
        }
}



int main()
{
 //resize scale
 int s=4;

 unsigned long AAtime=0, BBtime=0;

 //variables
 Mat GetImg, flow_x, flow_y, next, prvs;
 
 //gpu variable
 gpu::GpuMat prvs_gpu, next_gpu, flow_x_gpu, flow_y_gpu;
 gpu::GpuMat prvs_gpu_o, next_gpu_o;
 gpu::GpuMat prvs_gpu_c, next_gpu_c;

 //file name
 char fileName[100] = ".\\mm2.avi"; //Gate1_175_p1.avi"; //video\\mm2.avi"; //mm2.avi"; //cctv 2.mov"; //mm2.avi"; //";//_p1.avi";
 //video file open
 VideoCapture stream1(fileName);   //0 is the id of video device.0 if you have only one camera   
 if(!(stream1.read(GetImg))) //get one frame form video
  return 0;



 //////////////////////////////////////////////////////////////////////////////////////////////
 //resize(GetImg, prvs, Size(GetImg.size().width/s, GetImg.size().height/s) );
 //cvtColor(prvs, prvs, CV_BGR2GRAY);
 //prvs_gpu.upload(prvs);
 //////////////////////////////////////////////////////////////////////////////////////////////
 //gpu upload, resize, color convert
 prvs_gpu_o.upload(GetImg);
 gpu::resize(prvs_gpu_o, prvs_gpu_c, Size(GetImg.size().width/s, GetImg.size().height/s) );
 gpu::cvtColor(prvs_gpu_c, prvs_gpu, CV_BGR2GRAY);
 /////////////////////////////////////////////////////////////////////////////////////////////

 //dense optical flow
 gpu::FarnebackOpticalFlow fbOF;

 //unconditional loop   
 while (true) {   
  
  if(!(stream1.read(GetImg))) //get one frame form video   
   break;

  ///////////////////////////////////////////////////////////////////
  //resize(GetImg, next, Size(GetImg.size().width/s, GetImg.size().height/s) );
  //cvtColor(next, next, CV_BGR2GRAY);
  //next_gpu.upload(next);
  ///////////////////////////////////////////////////////////////////
  //gpu upload, resize, color convert
  next_gpu_o.upload(GetImg);
  gpu::resize(next_gpu_o, next_gpu_c, Size(GetImg.size().width/s, GetImg.size().height/s) );
  gpu::cvtColor(next_gpu_c, next_gpu, CV_BGR2GRAY);
  ///////////////////////////////////////////////////////////////////

  AAtime = getTickCount();
  //dense optical flow
  fbOF.operator()(prvs_gpu, next_gpu, flow_x_gpu, flow_y_gpu);
  //fbOF(prvs_gpu, next_gpu, flow_x_gpu, flow_y_gpu);
  BBtime = getTickCount();
  float pt = (BBtime - AAtime)/getTickFrequency();
  float fpt = 1/pt;
  printf("%.2lf / %.2lf \n",  pt, fpt );

  //copy for vector flow drawing
  Mat cflow;
  resize(GetImg, cflow, Size(GetImg.size().width/s, GetImg.size().height/s) );
  flow_x_gpu.download( flow_x );
  flow_y_gpu.download( flow_y );
  drawOptFlowMap_gpu(flow_x, flow_y, cflow, 10 , CV_RGB(0, 255, 0));
  imshow("OpticalFlowFarneback", cflow);

  ///////////////////////////////////////////////////////////////////
  //Display gpumat
  next_gpu.download( next );
  prvs_gpu.download( prvs );
  imshow("next", next );
  imshow("prvs", prvs );

  //prvs mat update
  prvs_gpu = next_gpu.clone();
  
  if (waitKey(5) >= 0)   
   break;
 }
}



4/25/2014

(OpenCV Study) calcOpticalFlowFarneback example source code ( dense optical flow )

refer to this web page
-> http://docs.opencv.org/trunk/doc/py_tutorials/py_video/py_lucas_kanade/py_lucas_kanade.html


dense optical flow is little bit different with feature tracking optical flow.
It search vector flow of all pixels.

In the output flow Mat, included vector point from self current point.
ex) The value of the flow Mat is 30,30 at the position of 20,20. The is directed to the from 20,20 to 30,30

The example source code draws direction of all pixels.
Drawing function is referenced from this site. http://stackoverflow.com/questions/16672003/how-to-extract-velocity-vectors-of-a-pixels-from-calcopticalflowfarneback






Disadvantage is the function is very slow.. gpu version function need. gpu mode source code is here-> http://www.youtube.com/watch?v=tg0oj4ObHlc&feature=youtu.be example soruce code here ->
#include < stdio.h>
#include < iostream>

#include < opencv2\opencv.hpp>
#include < opencv2/core/core.hpp>
#include < opencv2/highgui/highgui.hpp>
#include < opencv2/video/background_segm.hpp>


#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing
#pragma comment(lib, "opencv_objdetect247d.lib") //HOGDescriptor
//#pragma comment(lib, "opencv_gpu247d.lib")
//#pragma comment(lib, "opencv_features2d247d.lib")
#pragma comment(lib, "opencv_highgui247d.lib")
#pragma comment(lib, "opencv_ml247d.lib")
//#pragma comment(lib, "opencv_stitching247d.lib");
//#pragma comment(lib, "opencv_nonfree247d.lib");
#pragma comment(lib, "opencv_video247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_objdetect247.lib")
//#pragma comment(lib, "opencv_gpu247.lib")
//#pragma comment(lib, "opencv_features2d247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#pragma comment(lib, "opencv_ml247.lib")
//#pragma comment(lib, "opencv_stitching247.lib");
//#pragma comment(lib, "opencv_nonfree247.lib");
#pragma comment(lib, "opencv_video247d.lib")
#endif 

using namespace cv;
using namespace std;


void drawOptFlowMap (const Mat& flow, Mat& cflowmap, int step, const Scalar& color) {
 for(int y = 0; y < cflowmap.rows; y += step)
        for(int x = 0; x < cflowmap.cols; x += step)
        {
            const Point2f& fxy = flow.at< Point2f>(y, x);
            line(cflowmap, Point(x,y), Point(cvRound(x+fxy.x), cvRound(y+fxy.y)),
                 color);
            circle(cflowmap, Point(cvRound(x+fxy.x), cvRound(y+fxy.y)), 1, color, -1);
        }
    }


int main()
{
 int s=5;
 //global variables
 Mat GetImg;
 Mat prvs, next; //current frame
 
 char fileName[100] = "mm2.avi"; //video\\mm2.avi"; //mm2.avi"; //cctv 2.mov"; //mm2.avi"; //";//_p1.avi";
 VideoCapture stream1(fileName);   //0 is the id of video device.0 if you have only one camera   

 if(!(stream1.read(GetImg))) //get one frame form video
  return 0;
 resize(GetImg, prvs, Size(GetImg.size().width/s, GetImg.size().height/s) );
 cvtColor(prvs, prvs, CV_BGR2GRAY);

 //unconditional loop   
 while (true) {   
  
  if(!(stream1.read(GetImg))) //get one frame form video   
   break;
  //Resize
  resize(GetImg, next, Size(GetImg.size().width/s, GetImg.size().height/s) );
  cvtColor(next, next, CV_BGR2GRAY);
  ///////////////////////////////////////////////////////////////////
  Mat flow;
  calcOpticalFlowFarneback(prvs, next, flow, 0.5, 3, 15, 3, 5, 1.2, 0);

  Mat cflow;
  cvtColor(prvs, cflow, CV_GRAY2BGR);
  drawOptFlowMap(flow, cflow, 10, CV_RGB(0, 255, 0));
  imshow("OpticalFlowFarneback", cflow);

  ///////////////////////////////////////////////////////////////////
  //Display
  imshow("prvs", prvs);
  imshow("next", next);

  if (waitKey(5) >= 0)   
   break;

  prvs = next.clone();
 }

}



...

This video is result of source code.

(OpenCV Study) Background subtraction and Draw blob to red rectangle (example source code)

I use MOG2 algorithm to background subtraction.

The process is
resize to small for more fast processing
to blur for avoid noise affection
morphology make blob and remove noise
findContour to draw blob rectangle

Example movie of result.
more detail refer to source code..
#include < stdio.h>
#include < iostream>

#include < opencv2\opencv.hpp>
#include < opencv2/core/core.hpp>
#include < opencv2/highgui/highgui.hpp>
#include < opencv2/video/background_segm.hpp>


#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing
#pragma comment(lib, "opencv_objdetect247d.lib") //HOGDescriptor
//#pragma comment(lib, "opencv_gpu247d.lib")
//#pragma comment(lib, "opencv_features2d247d.lib")
#pragma comment(lib, "opencv_highgui247d.lib")
#pragma comment(lib, "opencv_ml247d.lib")
//#pragma comment(lib, "opencv_stitching247d.lib");
//#pragma comment(lib, "opencv_nonfree247d.lib");
#pragma comment(lib, "opencv_video247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_objdetect247.lib")
//#pragma comment(lib, "opencv_gpu247.lib")
//#pragma comment(lib, "opencv_features2d247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#pragma comment(lib, "opencv_ml247.lib")
//#pragma comment(lib, "opencv_stitching247.lib");
//#pragma comment(lib, "opencv_nonfree247.lib");
#pragma comment(lib, "opencv_video247d.lib")
#endif 

using namespace cv;
using namespace std;



int main()
{

 //global variables
 Mat frame; //current frame
 Mat resize_blur_Img;
 Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method
 Mat binaryImg;
 //Mat TestImg;
 Mat ContourImg; //fg mask fg mask generated by MOG2 method
 Ptr< BackgroundSubtractor> pMOG2; //MOG2 Background subtractor
 
 pMOG2 = new BackgroundSubtractorMOG2(300,32,true);//300,0.0);
 
 char fileName[100] = "mm2.avi"; //video\\mm2.avi"; //mm2.avi"; //cctv 2.mov"; //mm2.avi"; //";//_p1.avi";
 VideoCapture stream1(fileName);   //0 is the id of video device.0 if you have only one camera   

 //morphology element
 Mat element = getStructuringElement(MORPH_RECT, Size(7, 7), Point(3,3) );   

 //unconditional loop   
 while (true) {   
  Mat cameraFrame;   
  if(!(stream1.read(frame))) //get one frame form video   
   break;
  
  //Resize
  resize(frame, resize_blur_Img, Size(frame.size().width/3, frame.size().height/3) );
  //Blur
  blur(resize_blur_Img, resize_blur_Img, Size(4,4) );
  //Background subtraction
  pMOG2->operator()(resize_blur_Img, fgMaskMOG2, -1);//,-0.5);
  
  ///////////////////////////////////////////////////////////////////
  //pre procesing
  //1 point delete
  //morphologyEx(fgMaskMOG2, fgMaskMOG2, CV_MOP_ERODE, element);
  morphologyEx(fgMaskMOG2, binaryImg, CV_MOP_CLOSE, element);
  //morphologyEx(fgMaskMOG2, testImg, CV_MOP_OPEN, element);

  //Shadow delete
  //Binary
  threshold(binaryImg, binaryImg, 128, 255, CV_THRESH_BINARY);

  //Find contour
  ContourImg = binaryImg.clone();
  //less blob delete
  vector< vector< Point> > contours;
  findContours(ContourImg,
            contours, // a vector of contours
            CV_RETR_EXTERNAL, // retrieve the external contours
            CV_CHAIN_APPROX_NONE); // all pixels of each contours

  vector< Rect > output;
  vector< vector< Point> >::iterator itc= contours.begin();
  while (itc!=contours.end()) {

   //Create bounding rect of object
   //rect draw on origin image
   Rect mr= boundingRect(Mat(*itc));
   rectangle(resize_blur_Img, mr, CV_RGB(255,0,0));
   ++itc;
  }
  

  ///////////////////////////////////////////////////////////////////

  //Display
  imshow("Shadow_Removed", binaryImg);
  imshow("Blur_Resize", resize_blur_Img);
  imshow("MOG2", fgMaskMOG2);

  if (waitKey(5) >= 0)   
   break;   
 }

}



4/24/2014

(OpenCV Study) Background subtractor MOG, MOG2, GMG example source code (BackgroundSubtractorMOG, BackgroundSubtractorMOG2, BackgroundSubtractorGMG)

Background subtractor example souce code.

OpenCV support about 3 types subtraction algorithm.

Those are MOG, MOG2, GMG algorithms.

Detailed algorithm explain is, please refer to opencv documnet.

In this post, just introduce source code and result of background subtraction.

firstly, see the results of 3 algorithms.

origin image

MOG result

MOG2 result

CMG result




Especially, in MOG2 result, we can see the gray pixel color, that means shadow.
This is result video of the source code.
source code is here->  

#include < stdio.h>
#include < iostream>

#include < opencv2\opencv.hpp>
#include < opencv2/core/core.hpp>
#include < opencv2/highgui/highgui.hpp>
#include < opencv2/video/background_segm.hpp>


#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing
#pragma comment(lib, "opencv_objdetect247d.lib") //HOGDescriptor
//#pragma comment(lib, "opencv_gpu247d.lib")
//#pragma comment(lib, "opencv_features2d247d.lib")
#pragma comment(lib, "opencv_highgui247d.lib")
#pragma comment(lib, "opencv_ml247d.lib")
//#pragma comment(lib, "opencv_stitching247d.lib");
//#pragma comment(lib, "opencv_nonfree247d.lib");
#pragma comment(lib, "opencv_video247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_objdetect247.lib")
//#pragma comment(lib, "opencv_gpu247.lib")
//#pragma comment(lib, "opencv_features2d247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#pragma comment(lib, "opencv_ml247.lib")
//#pragma comment(lib, "opencv_stitching247.lib");
//#pragma comment(lib, "opencv_nonfree247.lib");
#pragma comment(lib, "opencv_video247d.lib")
#endif 

using namespace cv;
using namespace std;



int main()
{

 //global variables
 Mat frame; //current frame
 Mat resizeF;
 Mat fgMaskMOG; //fg mask generated by MOG method
 Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method
 Mat fgMaskGMG; //fg mask fg mask generated by MOG2 method
 

 Ptr< BackgroundSubtractor> pMOG; //MOG Background subtractor
 Ptr< BackgroundSubtractor> pMOG2; //MOG2 Background subtractor
 Ptr< BackgroundSubtractorGMG> pGMG; //MOG2 Background subtractor
 


 pMOG = new BackgroundSubtractorMOG();
 pMOG2 = new BackgroundSubtractorMOG2();
 pGMG = new BackgroundSubtractorGMG();
 

 char fileName[100] = "C:\\POSCO\\video\\/cctv 2.mov"; //Gate1_175_p1.avi"; //mm2.avi"; //";//_p1.avi";
 VideoCapture stream1(fileName);   //0 is the id of video device.0 if you have only one camera   

 Mat element = getStructuringElement(MORPH_RECT, Size(3, 3), Point(1,1) );   

 //unconditional loop   
 while (true) {   
  Mat cameraFrame;   
  if(!(stream1.read(frame))) //get one frame form video   
   break;
  
  resize(frame, resizeF, Size(frame.size().width/4, frame.size().height/4) );
  pMOG->operator()(resizeF, fgMaskMOG);
  pMOG2->operator()(resizeF, fgMaskMOG2);
  pGMG->operator()(resizeF, fgMaskGMG);
  //morphologyEx(fgMaskGMG, fgMaskGMG, CV_MOP_OPEN, element); 

 


  imshow("Origin", resizeF);
  imshow("MOG", fgMaskMOG);
  imshow("MOG2", fgMaskMOG2);
  imshow("GMG", fgMaskGMG);
  

  if (waitKey(30) >= 0)   
   break;   
 }

}




..


refer to this url that is 3.2 version example.
http://study.marearts.com/2017/04/opencv-background-subtraction-32.html