利用CodeBook算法實現目標檢測。
測試代碼:
// picturepreprocess.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <fstream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/video/background_segm.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <cvaux.h>
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;i<ImaskCodeBook->width;i++)
//{
//for (int j=0;j<ImaskCodeBook->height;j++)
//{
// p=cvGet2D(ImaskCodeBook,j,i);
//outfile<<p.val[0]<<"";
//}
//outfile<<endl;
//}
cvShowImage("Foreground_ConnectComp",ImaskCodeBookCC);
char c=cvWaitKey(30);
if(c==27) //按下Esc鍵退出視頻播放
break;
}
}
cvReleaseCapture( &capture );
cvDestroyWindow( "Raw" );
cvDestroyWindow( "Foreground");
cvDestroyWindow( "Foreground_ConnectComp");
}
測試效果: