CodeBook算法的基本思想是获得每一个像素的时间序列模型。这种模型能很好地处理时间起伏,缺点是须要消耗大量的内存。CodeBook算法为当前图像的每个像素创建一个CodeBook(CB)结构,每一个CodeBook结构又由多个CodeWord(CW)组成。
CB和CW的形式以下:
CB={CW1,CW2,…CWn,t}
CW={lHigh,lLow,max,min,t_last,stale}
其中n为一个CB中所包含的CW的数目,当n过小时,退化为简单背景,当n较大时能够对复杂背景进行建模;t为CB更新的次数。CW是一个6元组,其中IHigh和ILow做为更新时的学习上下界,max和min记录当前像素的最大值和最小值。上次更新的时间t_last和陈旧时间stale(记录该CW多久未被访问)用来删除不多使用的CodeWord。
假设当前训练图像I中某一像素为I(x,y),该像素的CB的更新算法以下,另外记背景阈值的增加断定阈值为Bounds:
(1) CB的访问次数加1;
(2) 遍历CB中的每一个CW,若是存在一个CW中的IHigh,ILow知足ILow≤I(x,y)≤ IHigh,则转(4);
(3) 建立一个新的码字CWnew加入到CB中, CWnew的max与min都赋值为I(x,y), IHigh <- I(x,y) + Bounds,ILow <- I(x,y) – Bounds,而且转(6);
(4) 更新该码字的t_last,若当前像素值I(x,y)大于该码字的max,则max <- I(x,y),若 I(x,y)小于该码字的min,则min <- I(x,y);
(5) 更新该码字的学习上下界,以增长背景模型对于复杂背景的适应能力,具体作法是: 若IHigh < I(x,y) + Bounds,则IHigh 增加1,若ILow > I(x,y) – Bounds,则ILow 减小1;
(6) 更新CB中每一个CW的stale。
使用已创建好的CB进行运动目标检测的方法很简单,记判断前景的范围上下界为minMod和maxMod,对于当前待检测图像上的某一像素I(x,y),遍历它对应像素背景模型CB中的每个码字CW,若存在一个CW,使得I(x,y) < max + maxMod而且I(x,y) > min – minMod,则I(x,y)被判断为背景,不然被判断为前景。
在实际使用CodeBook进行运动检测时,除了要隔必定的时间对CB进行更新的同时,须要对CB进行一个时间滤波,目的是去除不多被访问到的CW,其方法是访问每一个CW的stale,若stale大于一个阈值(一般设置为总更新次数的一半),移除该CW。
综上所述,CodeBook算法检测运动目标的流程以下:
(1) 选择一帧到多帧使用更新算法创建CodeBook背景模型;
(2) 按上面所述方法检测前景(运动目标);
(3) 间隔必定时间使用更新算法更新CodeBook模型,并对CodeBook进行时间滤波;
(4) 若检测继续,转(2),不然结束。ios
codebookWithOpenCV2.hc++
#ifndef ___CODEBOOKWITHOPENCV2_H___ #define ___CODEBOOKWITHOPENCV2_H___ #include <iostream> #include <list> #include <opencv2/opencv.hpp> #define CHANNELS 3 using namespace std; using namespace cv; class CodeWord { public: uchar learnHigh[CHANNELS]; // High side threshold for learning // 此码元各通道的阀值上限(背景学习建模界限) uchar learnLow[CHANNELS]; // Low side threshold for learning // 此码元各通道的阀值下限() // 学习过程当中若是一个新像素各通道值x[i],均有 learnLow[i]<=x[i]<=learnHigh[i],则该像素可合并于此码元 uchar max[CHANNELS]; // High side of box boundary 实际最大值 // 属于此码元的像素中各通道的最大值(判断过程的界限) uchar min[CHANNELS]; // Low side of box boundary 实际最小值 // 属于此码元的像素中各通道的最小值 int t_last_update; // This is book keeping to allow us to kill stale entries // 此码元最后一次更新的时间,每一帧为一个单位时间,用于计算stale int stale; // max negative run (biggest period of inactivity) // 此码元最长不更新时间,用于删除规定时间不更新的码元,精简码本 }; class CodeBook { public: list<CodeWord> codeElement; //考虑到方便的删除旧码元节点,同时访问码元的时候只须要顺序遍历,选用STL中的List,避免用指针。 int numEntries; // 此码本中码元的数目 int t; // count every access // 此码本如今的时间,一帧为一个时间单位 // 码本的数据结构 }; class BackgroundSubtractorCodeBook { public: BackgroundSubtractorCodeBook(); void updateCodeBook(const Mat &inputImage);//背景建模 void initialize(const Mat &inputImagee,Mat &outputImage);//获取第一帧,进行初始化 void clearStaleEntries();//清除旧的码元 void backgroudDiff(const Mat &inputImage,Mat &outputImage);//背景前景判断 ~BackgroundSubtractorCodeBook(); private: Mat yuvImage; Mat maskImage; CodeBook* codebookVec; //原本想用Vector,不用数组指针,可是codebook定长,不用增减,vector也很差初始化。 unsigned cbBounds[CHANNELS]; //背景建模时,用于创建学习的上下界限 uchar* pColor; //yuvImage pointer 通道指针 uchar* pMask;// maskImage pointer int imageSize; int nChannels; int minMod[CHANNELS]; //判断背景或者前景所用调节阈值 int maxMod[CHANNELS]; uchar maskPixelCodeBook; void _updateCodeBookPerPixel(int pixelIndex); void _clearStaleEntriesPerPixel(int pixelIndex); uchar _backgroundDiff(int pixelIndex); }; #endif
codebookWithOpenCV2.cpp算法
#include "codebookWithOpenCV2.h" BackgroundSubtractorCodeBook::BackgroundSubtractorCodeBook() {
nChannels=CHANNELS; } //初始化maskImage,codebook数组,将每一个像素的codebook的码元个数置0,初始化建模阈值和分割阈值 void BackgroundSubtractorCodeBook::initialize(const Mat &inputRGBImage,Mat &outputImage) { if (inputRGBImage.empty()) { return ; } if (yuvImage.empty()) { yuvImage.create(inputRGBImage.size(),inputRGBImage.type()); } if (maskImage.empty()) { maskImage.create(inputRGBImage.size(),CV_8UC1); Mat temp(inputRGBImage.rows,inputRGBImage.cols,CV_8UC1,Scalar::all(255)); maskImage=temp; } imageSize=inputRGBImage.cols*inputRGBImage.rows; codebookVec=new CodeBook[imageSize]; for (int i=0;i<imageSize;++i) { codebookVec[i].numEntries=0; }//初始化码元个数 for (int i=0; i<nChannels; i++) { cbBounds[i] = 10; // 用于肯定码元各通道的建模阀值 minMod[i] = 20; // 用于背景差分函数中 maxMod[i] = 20; // 调整其值以达到最好的分割 } outputImage=maskImage; } //逐个像素建模 void BackgroundSubtractorCodeBook::updateCodeBook(const Mat &inputImage) { cvtColor(inputImage,yuvImage,CV_RGB2YCrCb); pColor=yuvImage.data; for (int c=0;c<imageSize;++c) { _updateCodeBookPerPixel(c); pColor+=3; } } //单个像素建模实现函数,遍历全部码元,分三通道匹配,若知足,则更新该码元的时间,最大,最小值 //若不匹配,则建立新的码元。 void BackgroundSubtractorCodeBook::_updateCodeBookPerPixel(int pixelIndex) { if (codebookVec[pixelIndex].numEntries==0) { codebookVec[pixelIndex].t=0; } codebookVec[pixelIndex].t+=1; int n; unsigned int high[3],low[3]; for (n=0; n<nChannels; n++) //处理三通道的三个像素 { high[n] = *(pColor+n) + *(cbBounds+n); // *(p+n) 和 p[n] 结果等价,经试验*(p+n) 速度更快 if(high[n] > 255) high[n] = 255; low[n] = *(pColor+n)-*(cbBounds+n); if(low[n] < 0) low[n] = 0; // 用p 所指像素通道数据,加减cbBonds中数值,做为此像素阀值的上下限 } int matchChannel; list<CodeWord>::iterator jList; list<CodeWord>::iterator jListAfterPush; for (jList=codebookVec[pixelIndex].codeElement.begin();jList!=codebookVec[pixelIndex].codeElement.end();++jList) { // 遍历此码本每一个码元,测试p像素是否知足其中之一 matchChannel = 0; for (n=0; n<nChannels; n++) //遍历每一个通道 { if(((*jList).learnLow[n]<= *(pColor+n)) && (*(pColor+n) <= (*jList).learnHigh[n])) //Found an entry for this channel // 若是p 像素通道数据在该码元阀值上下限之间 { matchChannel++; } } if (matchChannel == nChannels) // If an entry was found over all channels // 若是p 像素各通道都知足上面条件 { (*jList).t_last_update = codebookVec[pixelIndex].t; // 更新该码元时间为当前时间 // adjust this codeword for the first channel for (n=0; n<nChannels; n++) //调整该码元各通道最大最小值 { if ((*jList).max[n] < *(pColor+n)) (*jList).max[n] = *(pColor+n); else if ((*jList).min[n] > *(pColor+n)) (*jList).min[n] = *(pColor+n); } break;//若是知足其中一个码元,则退出循环。 } } // ENTER A NEW CODE WORD IF NEEDED if(jList==codebookVec[pixelIndex].codeElement.end()) // No existing code word found, make a new one // p 像素不知足此码本中任何一个码元,下面建立一个新码元 { CodeWord newElement; for(n=0; n<nChannels; n++) // 更新新码元各通道数据 { newElement.learnHigh[n] = high[n]; newElement.learnLow[n] = low[n]; newElement.max[n] = *(pColor+n); newElement.min[n] = *(pColor+n); } newElement.t_last_update = codebookVec[pixelIndex].t; newElement.stale = 0; codebookVec[pixelIndex].numEntries += 1; codebookVec[pixelIndex].codeElement.push_back(newElement);//新的码元加入链表的最后。 } // OVERHEAD TO TRACK POTENTIAL STALE ENTRIES for (jListAfterPush=codebookVec[pixelIndex].codeElement.begin(); jListAfterPush!=codebookVec[pixelIndex].codeElement.end();++jListAfterPush) { // This garbage is to track which codebook entries are going stale int negRun = codebookVec[pixelIndex].t - (*jListAfterPush).t_last_update; // 计算该码元的不更新时间 if((*jListAfterPush).stale < negRun) (*jListAfterPush).stale = negRun; } // SLOWLY ADJUST LEARNING BOUNDS //对符合的码元进行更新,刚创建的码元确定不知足条件,不用考虑 for(n=0; n<nChannels; n++) // 若是像素通道数据在高低阀值范围内,但在码元阀值以外,则缓慢调整此码元学习界限 { if((*jList).learnHigh[n] < high[n]) (*jList).learnHigh[n] += 1;//+1是什么意思?缓慢调整? if((*jList).learnLow[n] > low[n]) (*jList).learnLow[n] -= 1; } return; } void BackgroundSubtractorCodeBook::clearStaleEntries() { for (int i=0;i<imageSize;++i) { _clearStaleEntriesPerPixel(i); } } void BackgroundSubtractorCodeBook::_clearStaleEntriesPerPixel(int pixelIndex) { int staleThresh=codebookVec[pixelIndex].t; for (list<CodeWord>::iterator itor=codebookVec[pixelIndex].codeElement.begin(); itor!=codebookVec[pixelIndex].codeElement.end();) { if ((*itor).stale>staleThresh) { itor=codebookVec[pixelIndex].codeElement.erase(itor);//erase以后返回被删的下一个元素的位置 } else { (*itor).stale=0; (*itor).t_last_update=0; itor++; } } codebookVec[pixelIndex].t=0;//码本时间清零; codebookVec[pixelIndex].numEntries=(int)codebookVec[pixelIndex].codeElement.size(); return; } void BackgroundSubtractorCodeBook:: backgroudDiff(const Mat &inputImage,Mat &outputImage) { cvtColor(inputImage,yuvImage,CV_RGB2YCrCb); pColor=yuvImage.data; pMask =maskImage.data; for(int c=0; c<imageSize; c++) { maskPixelCodeBook = _backgroundDiff(c); *pMask++ = maskPixelCodeBook; pColor += 3; // pColor 指向的是3通道图像 } outputImage=maskImage.clone(); } uchar BackgroundSubtractorCodeBook::_backgroundDiff(int pixelIndex) { int matchChannels; list<CodeWord>::iterator itor; for (itor=codebookVec[pixelIndex].codeElement.begin(); itor!=codebookVec[pixelIndex].codeElement.end();++itor) { matchChannels=0; for (int n=0;n<nChannels;++n) { if (((*itor).min[n] - minMod[n] <= *(pColor+n)) && (*(pColor+n) <=(*itor).max[n] + maxMod[n])) //相对于背景学习,这里是与码元中的最大最小值比较,并加入了余量minMod,maxMod; matchChannels++; //Found an entry for this channel else break;//一个通道没匹配,直接退出 } if (matchChannels == nChannels) break; //Found an entry that matched all channels,肯定是背景像素 返回0 黑色 } if (itor==codebookVec[pixelIndex].codeElement.end()) { return(255); } return (0); } BackgroundSubtractorCodeBook::~BackgroundSubtractorCodeBook() { delete [] codebookVec; }
codebookTest.cpp数组
#include "codebookWithOpenCV2.h" int main() { VideoCapture cap; cap.open("people.avi"); if( !cap.isOpened() ) { printf("can not open video file\n"); return -1; } namedWindow("image", WINDOW_NORMAL); namedWindow("foreground mask", WINDOW_NORMAL); BackgroundSubtractorCodeBook bgcbModel; Mat inputImage,outputMaskCodebook; for(int i=0;;++i) { cap>>inputImage; if( inputImage.empty() ) break; if(i==0) { bgcbModel.initialize(inputImage,outputMaskCodebook); } else if (i<=30&&i>0) { bgcbModel.updateCodeBook(inputImage); if (i==30) { bgcbModel.clearStaleEntries(); } } else { bgcbModel.backgroudDiff(inputImage,outputMaskCodebook); } imshow("image",inputImage); imshow("foreground mask",outputMaskCodebook); int c = waitKey(30); if (c == 'q' || c == 'Q' || (c & 255) == 27) break; } return 0; }
代码是参考以下翻译过来的。数据结构
/************************************************************************/ /* A few more thoughts on codebook models In general, the codebook method works quite well across a wide number of conditions, and it is relatively quick to train and to run. It doesn’t deal well with varying patterns of light — such as morning, noon, and evening sunshine — or with someone turning lights on or off indoors. This type of global variability can be taken into account by using several different codebook models, one for each condition, and then allowing the condition to control which model is active. */ /************************************************************************/ #include "stdafx.h" #include <cv.h> #include <highgui.h> #include <cxcore.h> #define CHANNELS 3 // 设置处理的图像通道数,要求小于等于图像自己的通道数 /////////////////////////////////////////////////////////////////////////// // 下面为码本码元的数据结构 // 处理图像时每一个像素对应一个码本,每一个码本中可有若干个码元 // 当涉及一个新领域,一般会遇到一些奇怪的名词,不要被这些名词吓坏,其实思路都是简单的 typedef struct ce { uchar learnHigh[CHANNELS]; // High side threshold for learning // 此码元各通道的阀值上限(学习界限) uchar learnLow[CHANNELS]; // Low side threshold for learning // 此码元各通道的阀值下限 // 学习过程当中若是一个新像素各通道值x[i],均有 learnLow[i]<=x[i]<=learnHigh[i],则该像素可合并于此码元 uchar max[CHANNELS]; // High side of box boundary // 属于此码元的像素中各通道的最大值 uchar min[CHANNELS]; // Low side of box boundary // 属于此码元的像素中各通道的最小值 int t_last_update; // This is book keeping to allow us to kill stale entries // 此码元最后一次更新的时间,每一帧为一个单位时间,用于计算stale int stale; // max negative run (biggest period of inactivity) // 此码元最长不更新时间,用于删除规定时间不更新的码元,精简码本 } code_element; // 码元的数据结构 typedef struct code_book { code_element **cb; // 码元的二维指针,理解为指向码元指针数组的指针,使得添加码元时不须要来回复制码元,只须要简单的指针赋值便可 int numEntries; // 此码本中码元的数目 int t; // count every access // 此码本如今的时间,一帧为一个时间单位 } codeBook; // 码本的数据结构 /////////////////////////////////////////////////////////////////////////////////// // int updateCodeBook(uchar *p, codeBook &c, unsigned cbBounds) // Updates the codebook entry with a new data point // // p Pointer to a YUV pixel // c Codebook for this pixel // cbBounds Learning bounds for codebook (Rule of thumb: 10) // numChannels Number of color channels we're learning // // NOTES: // cvBounds must be of size cvBounds[numChannels] // // RETURN // codebook index int cvupdateCodeBook(uchar *p, codeBook &c, unsigned *cbBounds, int numChannels) { if(c.numEntries == 0) c.t = 0; // 码本中码元为零时初始化时间为0 c.t += 1; // Record learning event // 每调用一次加一,即每一帧图像加一 //SET HIGH AND LOW BOUNDS int n; unsigned int high[3],low[3]; for (n=0; n<numChannels; n++) { high[n] = *(p+n) + *(cbBounds+n); // *(p+n) 和 p[n] 结果等价,经试验*(p+n) 速度更快 if(high[n] > 255) high[n] = 255; low[n] = *(p+n)-*(cbBounds+n); if(low[n] < 0) low[n] = 0; // 用p 所指像素通道数据,加减cbBonds中数值,做为此像素阀值的上下限 } //SEE IF THIS FITS AN EXISTING CODEWORD int matchChannel; int i; for (i=0; i<c.numEntries; i++) { // 遍历此码本每一个码元,测试p像素是否知足其中之一 matchChannel = 0; for (n=0; n<numChannels; n++) //遍历每一个通道 { if((c.cb[i]->learnLow[n] <= *(p+n)) && (*(p+n) <= c.cb[i]->learnHigh[n])) //Found an entry for this channel // 若是p 像素通道数据在该码元阀值上下限之间 { matchChannel++; } } if (matchChannel == numChannels) // If an entry was found over all channels // 若是p 像素各通道都知足上面条件 { c.cb[i]->t_last_update = c.t; // 更新该码元时间为当前时间 // adjust this codeword for the first channel for (n=0; n<numChannels; n++) //调整该码元各通道最大最小值 { if (c.cb[i]->max[n] < *(p+n)) c.cb[i]->max[n] = *(p+n); else if (c.cb[i]->min[n] > *(p+n)) c.cb[i]->min[n] = *(p+n); } break; } } // ENTER A NEW CODE WORD IF NEEDED if(i == c.numEntries) // No existing code word found, make a new one // p 像素不知足此码本中任何一个码元,下面建立一个新码元 { code_element **foo = new code_element* [c.numEntries+1]; // 申请c.numEntries+1 个指向码元的指针 for(int ii=0; ii<c.numEntries; ii++) // 将前c.numEntries 个指针指向已存在的每一个码元 foo[ii] = c.cb[ii]; foo[c.numEntries] = new code_element; // 申请一个新的码元 if(c.numEntries) delete [] c.cb; // 删除c.cb 指针数组 c.cb = foo; // 把foo 头指针赋给c.cb for(n=0; n<numChannels; n++) // 更新新码元各通道数据 { c.cb[c.numEntries]->learnHigh[n] = high[n]; c.cb[c.numEntries]->learnLow[n] = low[n]; c.cb[c.numEntries]->max[n] = *(p+n); c.cb[c.numEntries]->min[n] = *(p+n); } c.cb[c.numEntries]->t_last_update = c.t; c.cb[c.numEntries]->stale = 0; c.numEntries += 1; } // OVERHEAD TO TRACK POTENTIAL STALE ENTRIES for(int s=0; s<c.numEntries; s++) { // This garbage is to track which codebook entries are going stale int negRun = c.t - c.cb[s]->t_last_update; // 计算该码元的不更新时间 if(c.cb[s]->stale < negRun) c.cb[s]->stale = negRun; } // SLOWLY ADJUST LEARNING BOUNDS for(n=0; n<numChannels; n++) // 若是像素通道数据在高低阀值范围内,但在码元阀值以外,则缓慢调整此码元学习界限 { if(c.cb[i]->learnHigh[n] < high[n]) c.cb[i]->learnHigh[n] += 1; if(c.cb[i]->learnLow[n] > low[n]) c.cb[i]->learnLow[n] -= 1; } return(i); } /////////////////////////////////////////////////////////////////////////////////// // uchar cvbackgroundDiff(uchar *p, codeBook &c, int minMod, int maxMod) // Given a pixel and a code book, determine if the pixel is covered by the codebook // // p pixel pointer (YUV interleaved) // c codebook reference // numChannels Number of channels we are testing // maxMod Add this (possibly negative) number onto max level when code_element determining if new pixel is foreground // minMod Subract this (possible negative) number from min level code_element when determining if pixel is foreground // // NOTES: // minMod and maxMod must have length numChannels, e.g. 3 channels => minMod[3], maxMod[3]. // // Return // 0 => background, 255 => foreground uchar cvbackgroundDiff(uchar *p, codeBook &c, int numChannels, int *minMod, int *maxMod) { // 下面步骤和背景学习中查找码元一模一样 int matchChannel; //SEE IF THIS FITS AN EXISTING CODEWORD int i; for (i=0; i<c.numEntries; i++) { matchChannel = 0; for (int n=0; n<numChannels; n++) { if ((c.cb[i]->min[n] - minMod[n] <= *(p+n)) && (*(p+n) <= c.cb[i]->max[n] + maxMod[n])) matchChannel++; //Found an entry for this channel else break; } if (matchChannel == numChannels) break; //Found an entry that matched all channels } if(i == c.numEntries) // p像素各通道值知足码本中其中一个码元,则返回白色 return(255); return(0); } //UTILITES///////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// //int clearStaleEntries(codeBook &c) // After you've learned for some period of time, periodically call this to clear out stale codebook entries // //c Codebook to clean up // // Return // number of entries cleared int cvclearStaleEntries(codeBook &c) { int staleThresh = c.t >> 1; // 设定刷新时间 int *keep = new int [c.numEntries]; // 申请一个标记数组 int keepCnt = 0; // 记录不删除码元数目 //SEE WHICH CODEBOOK ENTRIES ARE TOO STALE for (int i=0; i<c.numEntries; i++) // 遍历码本中每一个码元 { if (c.cb[i]->stale > staleThresh) // 如码元中的不更新时间大于设定的刷新时间,则标记为删除 keep[i] = 0; //Mark for destruction else { keep[i] = 1; //Mark to keep keepCnt += 1; } } // KEEP ONLY THE GOOD c.t = 0; //Full reset on stale tracking // 码本时间清零 code_element **foo = new code_element* [keepCnt]; // 申请大小为keepCnt 的码元指针数组 int k=0; for(int ii=0; ii<c.numEntries; ii++) { if(keep[ii]) { foo[k] = c.cb[ii]; foo[k]->stale = 0; //We have to refresh these entries for next clearStale foo[k]->t_last_update = 0; k++; } } //CLEAN UP delete [] keep; delete [] c.cb; c.cb = foo; // 把foo 头指针地址赋给c.cb int numCleared = c.numEntries - keepCnt; // 被清理的码元个数 c.numEntries = keepCnt; // 剩余的码元地址 return(numCleared); } int main() { /////////////////////////////////////// // 须要使用的变量 CvCapture* capture; IplImage* rawImage; IplImage* yuvImage; IplImage* ImaskCodeBook; codeBook* cB; unsigned cbBounds[CHANNELS]; uchar* pColor; //YUV pointer int imageLen; int nChannels = CHANNELS; int minMod[CHANNELS]; int maxMod[CHANNELS]; ////////////////////////////////////////////////////////////////////////// // 初始化各变量 cvNamedWindow("Raw"); cvNamedWindow("CodeBook"); capture = cvCreateFileCapture("tree.avi"); if (!capture) { printf("Couldn't open the capture!"); return -1; } rawImage = cvQueryFrame(capture); yuvImage = cvCreateImage(cvGetSize(rawImage), 8, 3); // 给yuvImage 分配一个和rawImage 尺寸相同,8位3通道图像 ImaskCodeBook = cvCreateImage(cvGetSize(rawImage), IPL_DEPTH_8U, 1); // 为ImaskCodeBook 分配一个和rawImage 尺寸相同,8位单通道图像 cvSet(ImaskCodeBook, cvScalar(255)); // 设置单通道数组全部元素为255,即初始化为白色图像 imageLen = rawImage->width * rawImage->height; cB = new codeBook[imageLen]; // 获得与图像像素数目长度同样的一组码本,以便对每一个像素进行处理 for (int i=0; i<imageLen; i++) // 初始化每一个码元数目为0 cB[i].numEntries = 0; for (int i=0; i<nChannels; i++) { cbBounds[i] = 10; // 用于肯定码元各通道的阀值 minMod[i] = 20; // 用于背景差分函数中 maxMod[i] = 20; // 调整其值以达到最好的分割 } ////////////////////////////////////////////////////////////////////////// // 开始处理视频每一帧图像 for (int i=0;;i++) { cvCvtColor(rawImage, yuvImage, CV_BGR2YCrCb); // 色彩空间转换,将rawImage 转换到YUV色彩空间,输出到yuvImage // 即便不转换效果依然很好 // yuvImage = cvCloneImage(rawImage); if (i <= 30) // 30帧内进行背景学习 { pColor = (uchar *)(yuvImage->imageData); // 指向yuvImage 图像的通道数据 for (int c=0; c<imageLen; c++) { cvupdateCodeBook(pColor, cB[c], cbBounds, nChannels); // 对每一个像素,调用此函数,捕捉背景中相关变化图像 pColor += 3; // 3 通道图像, 指向下一个像素通道数据 } if (i == 30) // 到30 帧时调用下面函数,删除码本中陈旧的码元 { for (int c=0; c<imageLen; c++) cvclearStaleEntries(cB[c]); } } else { uchar maskPixelCodeBook; pColor = (uchar *)((yuvImage)->imageData); //3 channel yuv image uchar *pMask = (uchar *)((ImaskCodeBook)->imageData); //1 channel image // 指向ImaskCodeBook 通道数据序列的首元素 for(int c=0; c<imageLen; c++) { maskPixelCodeBook = cvbackgroundDiff(pColor, cB[c], nChannels, minMod, maxMod); // 我看到这儿时豁然开朗,开始理解了codeBook 呵呵 *pMask++ = maskPixelCodeBook; pColor += 3; // pColor 指向的是3通道图像 } } if (!(rawImage = cvQueryFrame(capture))) break; cvShowImage("Raw", rawImage); cvShowImage("CodeBook", ImaskCodeBook); if (cvWaitKey(30) == 27) break; if (i == 56 || i == 63) cvWaitKey(); } cvReleaseCapture(&capture); if (yuvImage) cvReleaseImage(&yuvImage); if(ImaskCodeBook) cvReleaseImage(&ImaskCodeBook); cvDestroyAllWindows(); delete [] cB; return 0; }
另外,在stackoverflow上找到的代码,未测试,可参考。ide
bgfg_cb.h函数
#ifndef __bgfg_cb_h__ #define __bgfg_cb_h__ //http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.148.9778&rep=rep1&type=pdf #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <time.h> using namespace cv; using namespace std; struct codeword { float min; float max; float f; float l; int first; int last; bool isStale; }; extern int alpha ; extern float beta ; extern int Tdel ,Tadd , Th; void initializeCodebook(int w,int h); void update_cb(Mat& frame); void fg_cb(Mat& frame,Mat& fg); #endif
bgfg_cb.cpp学习
#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <time.h> #include "bgfg_cb.h" using namespace cv; using namespace std; vector<codeword> **cbMain; vector<codeword> **cbCache; int t=0; int alpha = 10;//knob float beta =1; int Tdel = 200,Tadd = 150, Th= 200;//knobs void initializeCodebook(int w,int h) { cbMain = new vector<codeword>*[w]; for(int i = 0; i < w; ++i) cbMain[i] = new vector<codeword>[h]; cbCache = new vector<codeword>*[w]; for(int i = 0; i < w; ++i) cbCache[i] = new vector<codeword>[h]; } void update_cb(Mat& frame) { if(t>10) return; for(int i=0;i<frame.rows;i++) { for(int j=0;j<frame.cols;j++) { int pix = frame.at<uchar>(i,j); vector<codeword>& cm =cbMain[i][j]; bool found = false; for(int k=0;k<cm.size();k++) { if(cm[k].min<=pix && pix<=cm[k].max && !found) { found=true; cm[k].min = ((pix-alpha)+(cm[k].f*cm[k].min))/(cm[k].f+1); cm[k].max = ((pix+alpha)+(cm[k].f*cm[k].max))/(cm[k].f+1); cm[k].l=0; cm[k].last=t; cm[k].f++; }else { cm[k].l++; } } if(!found) { codeword n={}; n.min=max(0,pix-alpha); n.max=min(255,pix+alpha); n.f=1; n.l=0; n.first=t; n.last=t; cm.push_back(n); } } } t++; } void fg_cb(Mat& frame,Mat& fg) { fg=Mat::zeros(frame.size(),CV_8UC1); if(cbMain==0) initializeCodebook(frame.rows,frame.cols); if(t<10) { update_cb(frame); return; } for(int i=0;i<frame.rows;i++) { for(int j=0;j<frame.cols;j++) { int pix = frame.at<uchar>(i,j); vector<codeword>& cm = cbMain[i][j]; bool found = false; for(int k=0;k<cm.size();k++) { if(cm[k].min<=pix && pix<=cm[k].max && !found) { cm[k].min = ((1-beta)*(pix-alpha)) + (beta*cm[k].min); cm[k].max = ((1-beta)*(pix+alpha)) + (beta*cm[k].max); cm[k].l=0; cm[k].first=t; cm[k].f++; found=true; }else { cm[k].l++; } } cm.erase( remove_if(cm.begin(), cm.end(), [](codeword& c) { return c.l>=Tdel;} ), cm.end() ); fg.at<uchar>(i,j) = found?0:255; if(found) continue; found = false; vector<codeword>& cc = cbCache[i][j]; for(int k=0;k<cc.size();k++) { if(cc[k].min<=pix && pix<=cc[k].max && !found) { cc[k].min = ((1-beta)*(pix-alpha)) + (beta*cc[k].min); cc[k].max = ((1-beta)*(pix+alpha)) + (beta*cc[k].max); cc[k].l=0; cc[k].first=t; cc[k].f++; found=true; }else { cc[k].l++; } } if(!found) { codeword n={}; n.min=max(0,pix-alpha); n.max=min(255,pix+alpha); n.f=1; n.l=0; n.first=t; n.last=t; cc.push_back(n); } cc.erase( remove_if(cc.begin(), cc.end(), [](codeword& c) { return c.l>=Th;} ), cc.end() ); for(vector<codeword>::iterator it=cc.begin();it!=cc.end();it++) { if(it->f>Tadd) { cm.push_back(*it); } } cc.erase( remove_if(cc.begin(), cc.end(), [](codeword& c) { return c.f>Tadd;} ), cc.end() ); } } }
main.cpp测试
#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "bgfg_cb.h" #include <iostream> using namespace cv; using namespace std; void proc() { Mat frame,fg,gray; VideoCapture cap("C:/Downloads/S2_L1.tar/S2_L1/Crowd_PETS09/S2/L1/Time_12-34/View_001/frame_%04d.jpg"); cap >> frame; initializeCodebook(frame.rows,frame.cols); for(;;) { cap>>frame; cvtColor(frame,gray,CV_BGR2GRAY); fg_cb(gray,fg); Mat cc; imshow("fg",fg); waitKey(1); } } int main(int argc, char ** argv) { proc(); cin.ignore(1); return 0; }