目标检测——CodeBook 算法测试代码

利用CodeBook算法实现目标检测。
测试代码:


// picturepreprocess.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
using namespace cv;


//const int NCHANNELS = 3;
//bool ch[NCHANNELS]={true,true,true};


int _tmain(int argc, _TCHAR* argv[])
{
     //CvScalar p;
    //ofstream outfile("C:\\Users\\admin\\Desktop\\gray\\gray.txt");
    IplImage* rawImage = 0, *yuvImage = 0; 
    IplImage *ImaskCodeBook = 0,*ImaskCodeBookCC = 0;
    CvCapture* capture = 0;

    int nframes = 0;
    int nframesToLearnBG =200;//训练帧数选择
    CvBGCodeBookModel* model = 0;
    model = cvCreateBGCodeBookModel(); //codebook方法参数初始化(选择默认值)
    model->modMin[0] = 3;
    model->modMin[1] = model->modMin[2] = 3;
    model->modMax[0] = 10;
    model->modMax[1] = model->modMax[2] = 10;
    model->cbBounds[0] = model->cbBounds[1] = model->cbBounds[2] = 10;

    bool pause = false;

   cvNamedWindow( "Raw", 1 );
   cvNamedWindow( "Foreground",1);
   cvNamedWindow( "Foreground_ConnectComp",1);
   capture =cvCreateFileCapture(".....");//初始化从文件中获取视频 
  while(rawImage = cvQueryFrame( capture ))   
   {     
      nframes++;           
      if(nframes == 1)   
      {   
       yuvImage = cvCloneImage(rawImage);
       ImaskCodeBook = cvCreateImage(cvGetSize(rawImage), IPL_DEPTH_8U, 1 );
       ImaskCodeBookCC = cvCreateImage(cvGetSize(rawImage), IPL_DEPTH_8U, 1 );
       cvSet(ImaskCodeBook,cvScalar(255));

      }     
      else
      {
         cvCvtColor(rawImage, yuvImage, CV_BGR2YCrCb);
         if(!pause && nframes-1 < nframesToLearnBG)
                cvBGCodeBookUpdate( model, yuvImage ); 
         if(nframes-1 == nframesToLearnBG)
                cvBGCodeBookClearStale( model, model->t/2 );


         if( nframes-1 >= nframesToLearnBG){
                // 提取前景
                cvBGCodeBookDiff(model, yuvImage, ImaskCodeBook);//codebook方法中,背景减除
                // 对前景做连通域分割
                cvCopy(ImaskCodeBook,ImaskCodeBookCC);
                cvSegmentFGMask(ImaskCodeBookCC);
            }

            cvShowImage("Raw", rawImage);
            cvShowImage("Foreground",ImaskCodeBook);

//查看像素
            //for (int i=0;iwidth;i++)
            //{
                //for (int j=0;jheight;j++)
                //{

                   // p=cvGet2D(ImaskCodeBook,j,i);

                    //outfile<
                //}
                //outfile<
            //}

            cvShowImage("Foreground_ConnectComp",ImaskCodeBookCC);
             char c=cvWaitKey(30);
                if(c==27) //按下Esc键退出视频播放
                    break;
        }


    }

    cvReleaseCapture( &capture );
    cvDestroyWindow( "Raw" );
    cvDestroyWindow( "Foreground");
    cvDestroyWindow( "Foreground_ConnectComp");

}


测试效果:
目标检测——CodeBook 算法测试代码_第1张图片

你可能感兴趣的:(基于Opencv开发)