codebook 背景减除

来源:互联网 发布:php方面的书籍 编辑:程序博客网 时间:2024/05/16 07:50

56帧时

63帧时


/**
比平均背景法性能更加良好的方法,codeBook模型实现背景减除

核心代码详细解析和实现 by zcube
*/

[cpp] view plain copy
  1. /************************************************************************/  
  2. /*          A few more thoughts on codebook models 
  3. In general, the codebook method works quite well across a wide number of conditions,  
  4. and it is relatively quick to train and to run. It doesn’t deal well with varying patterns of  
  5. light — such as morning, noon, and evening sunshine — or with someone turning lights  
  6. on or off indoors. This type of global variability can be taken into account by using  
  7. several different codebook models, one for each condition, and then allowing the condition  
  8. to control which model is active.                                       */  
  9. /************************************************************************/  
  10.   
  11. #include "stdafx.h"  
  12. #include <cv.h>             
  13. #include <highgui.h>  
  14. #include <cxcore.h>  
  15.   
  16. #define CHANNELS 3        
  17. // 设置处理的图像通道数,要求小于等于图像本身的通道数  
  18.   
  19. ///////////////////////////////////////////////////////////////////////////  
  20. // 下面为码本码元的数据结构  
  21. // 处理图像时每个像素对应一个码本,每个码本中可有若干个码元  
  22. // 当涉及一个新领域,通常会遇到一些奇怪的名词,不要被这些名词吓坏,其实思路都是简单的  
  23. typedef struct ce {  
  24.     uchar   learnHigh[CHANNELS];    // High side threshold for learning  
  25.     // 此码元各通道的阀值上限(学习界限)  
  26.     uchar   learnLow[CHANNELS];     // Low side threshold for learning  
  27.     // 此码元各通道的阀值下限  
  28.     // 学习过程中如果一个新像素各通道值x[i],均有 learnLow[i]<=x[i]<=learnHigh[i],则该像素可合并于此码元  
  29.     uchar   max[CHANNELS];          // High side of box boundary  
  30.     // 属于此码元的像素中各通道的最大值  
  31.     uchar   min[CHANNELS];          // Low side of box boundary  
  32.     // 属于此码元的像素中各通道的最小值  
  33.     int     t_last_update;          // This is book keeping to allow us to kill stale entries  
  34.     // 此码元最后一次更新的时间,每一帧为一个单位时间,用于计算stale  
  35.     int     stale;                  // max negative run (biggest period of inactivity)  
  36.     // 此码元最长不更新时间,用于删除规定时间不更新的码元,精简码本  
  37. } code_element;                     // 码元的数据结构  
  38.   
  39. typedef struct code_book {  
  40.     code_element    **cb;  
  41.     // 码元的二维指针,理解为指向码元指针数组的指针,使得添加码元时不需要来回复制码元,只需要简单的指针赋值即可  
  42.     int             numEntries;  
  43.     // 此码本中码元的数目  
  44.     int             t;              // count every access  
  45.     // 此码本现在的时间,一帧为一个时间单位  
  46. } codeBook;                         // 码本的数据结构  
  47.   
  48.   
  49. ///////////////////////////////////////////////////////////////////////////////////  
  50. // int updateCodeBook(uchar *p, codeBook &c, unsigned cbBounds)  
  51. // Updates the codebook entry with a new data point  
  52. //  
  53. // p            Pointer to a YUV pixel  
  54. // c            Codebook for this pixel  
  55. // cbBounds     Learning bounds for codebook (Rule of thumb: 10)  
  56. // numChannels  Number of color channels we're learning  
  57. //  
  58. // NOTES:  
  59. //      cvBounds must be of size cvBounds[numChannels]  
  60. //  
  61. // RETURN  
  62. //  codebook index  
  63. int cvupdateCodeBook(uchar *p, codeBook &c, unsigned *cbBounds, int numChannels)  
  64. {  
  65.     if(c.numEntries == 0) c.t = 0;  
  66.     // 码本中码元为零时初始化时间为0  
  67.     c.t += 1;   // Record learning event  
  68.     // 每调用一次加一,即每一帧图像加一  
  69.       
  70.     //SET HIGH AND LOW BOUNDS  
  71.     int n;  
  72.     unsigned int high[3],low[3];  
  73.     for (n=0; n<numChannels; n++)  
  74.     {  
  75.         high[n] = *(p+n) + *(cbBounds+n);  
  76.         // *(p+n) 和 p[n] 结果等价,经试验*(p+n) 速度更快  
  77.         if(high[n] > 255) high[n] = 255;  
  78.         low[n] = *(p+n)-*(cbBounds+n);  
  79.         if(low[n] < 0) low[n] = 0;  
  80.         // 用p 所指像素通道数据,加减cbBonds中数值,作为此像素阀值的上下限  
  81.     }  
  82.   
  83.     //SEE IF THIS FITS AN EXISTING CODEWORD  
  84.     int matchChannel;     
  85.     int i;  
  86.     for (i=0; i<c.numEntries; i++)  
  87.     {  
  88.         // 遍历此码本每个码元,测试p像素是否满足其中之一  
  89.         matchChannel = 0;  
  90.         for (n=0; n<numChannels; n++)  
  91.             //遍历每个通道  
  92.         {  
  93.             if((c.cb[i]->learnLow[n] <= *(p+n)) && (*(p+n) <= c.cb[i]->learnHigh[n])) //Found an entry for this channel  
  94.             // 如果p 像素通道数据在该码元阀值上下限之间  
  95.             {     
  96.                 matchChannel++;  
  97.             }  
  98.         }  
  99.         if (matchChannel == numChannels)        // If an entry was found over all channels  
  100.             // 如果p 像素各通道都满足上面条件  
  101.         {  
  102.             c.cb[i]->t_last_update = c.t;  
  103.             // 更新该码元时间为当前时间  
  104.             // adjust this codeword for the first channel  
  105.             for (n=0; n<numChannels; n++)  
  106.                 //调整该码元各通道最大最小值  
  107.             {  
  108.                 if (c.cb[i]->max[n] < *(p+n))  
  109.                     c.cb[i]->max[n] = *(p+n);  
  110.                 else if (c.cb[i]->min[n] > *(p+n))  
  111.                     c.cb[i]->min[n] = *(p+n);  
  112.             }  
  113.             break;  
  114.         }  
  115.     }  
  116.   
  117.     // ENTER A NEW CODE WORD IF NEEDED  
  118.     if(i == c.numEntries)  // No existing code word found, make a new one  
  119.     // p 像素不满足此码本中任何一个码元,下面创建一个新码元  
  120.     {  
  121.         code_element **foo = new code_element* [c.numEntries+1];  
  122.         // 申请c.numEntries+1 个指向码元的指针  
  123.         for(int ii=0; ii<c.numEntries; ii++)  
  124.             // 将前c.numEntries 个指针指向已存在的每个码元  
  125.             foo[ii] = c.cb[ii];  
  126.           
  127.         foo[c.numEntries] = new code_element;  
  128.         // 申请一个新的码元  
  129.         if(c.numEntries) delete [] c.cb;  
  130.         // 删除c.cb 指针数组  
  131.         c.cb = foo;  
  132.         // 把foo 头指针赋给c.cb  
  133.         for(n=0; n<numChannels; n++)  
  134.             // 更新新码元各通道数据  
  135.         {  
  136.             c.cb[c.numEntries]->learnHigh[n] = high[n];  
  137.             c.cb[c.numEntries]->learnLow[n] = low[n];  
  138.             c.cb[c.numEntries]->max[n] = *(p+n);  
  139.             c.cb[c.numEntries]->min[n] = *(p+n);  
  140.         }  
  141.         c.cb[c.numEntries]->t_last_update = c.t;  
  142.         c.cb[c.numEntries]->stale = 0;  
  143.         c.numEntries += 1;  
  144.     }  
  145.   
  146.     // OVERHEAD TO TRACK POTENTIAL STALE ENTRIES  
  147.     for(int s=0; s<c.numEntries; s++)  
  148.     {  
  149.         // This garbage is to track which codebook entries are going stale  
  150.         int negRun = c.t - c.cb[s]->t_last_update;  
  151.         // 计算该码元的不更新时间  
  152.         if(c.cb[s]->stale < negRun)   
  153.             c.cb[s]->stale = negRun;  
  154.     }  
  155.   
  156.     // SLOWLY ADJUST LEARNING BOUNDS  
  157.     for(n=0; n<numChannels; n++)  
  158.         // 如果像素通道数据在高低阀值范围内,但在码元阀值之外,则缓慢调整此码元学习界限  
  159.     {  
  160.         if(c.cb[i]->learnHigh[n] < high[n])   
  161.             c.cb[i]->learnHigh[n] += 1;  
  162.         if(c.cb[i]->learnLow[n] > low[n])   
  163.             c.cb[i]->learnLow[n] -= 1;  
  164.     }  
  165.   
  166.     return(i);  
  167. }  
  168.   
  169. ///////////////////////////////////////////////////////////////////////////////////  
  170. // uchar cvbackgroundDiff(uchar *p, codeBook &c, int minMod, int maxMod)  
  171. // Given a pixel and a code book, determine if the pixel is covered by the codebook  
  172. //  
  173. // p        pixel pointer (YUV interleaved)  
  174. // c        codebook reference  
  175. // numChannels  Number of channels we are testing  
  176. // maxMod   Add this (possibly negative) number onto max level when code_element determining if new pixel is foreground  
  177. // minMod   Subract this (possible negative) number from min level code_element when determining if pixel is foreground  
  178. //  
  179. // NOTES:  
  180. // minMod and maxMod must have length numChannels, e.g. 3 channels => minMod[3], maxMod[3].  
  181. //  
  182. // Return  
  183. // 0 => background, 255 => foreground  
  184. uchar cvbackgroundDiff(uchar *p, codeBook &c, int numChannels, int *minMod, int *maxMod)  
  185. {  
  186.     // 下面步骤和背景学习中查找码元如出一辙  
  187.     int matchChannel;  
  188.     //SEE IF THIS FITS AN EXISTING CODEWORD  
  189.     int i;  
  190.     for (i=0; i<c.numEntries; i++)  
  191.     {  
  192.         matchChannel = 0;  
  193.         for (int n=0; n<numChannels; n++)  
  194.         {  
  195.             if ((c.cb[i]->min[n] - minMod[n] <= *(p+n)) && (*(p+n) <= c.cb[i]->max[n] + maxMod[n]))  
  196.                 matchChannel++; //Found an entry for this channel  
  197.             else  
  198.                 break;  
  199.         }  
  200.         if (matchChannel == numChannels)  
  201.             break//Found an entry that matched all channels  
  202.     }  
  203.     if(i == c.numEntries)   
  204.         // p像素各通道值满足码本中其中一个码元,则返回白色  
  205.         return(255);  
  206.   
  207.     return(0);  
  208. }  
  209.   
  210.   
  211. //UTILITES/////////////////////////////////////////////////////////////////////////////////////  
  212. /////////////////////////////////////////////////////////////////////////////////  
  213. //int clearStaleEntries(codeBook &c)  
  214. // After you've learned for some period of time, periodically call this to clear out stale codebook entries  
  215. //  
  216. //c     Codebook to clean up  
  217. //  
  218. // Return  
  219. // number of entries cleared  
  220. int cvclearStaleEntries(codeBook &c)  
  221. {  
  222.     int staleThresh = c.t >> 1;           // 设定刷新时间  
  223.     int *keep = new int [c.numEntries]; // 申请一个标记数组  
  224.     int keepCnt = 0;                    // 记录不删除码元数目  
  225.     //SEE WHICH CODEBOOK ENTRIES ARE TOO STALE  
  226.     for (int i=0; i<c.numEntries; i++)  
  227.         // 遍历码本中每个码元  
  228.     {  
  229.         if (c.cb[i]->stale > staleThresh)   
  230.             // 如码元中的不更新时间大于设定的刷新时间,则标记为删除  
  231.             keep[i] = 0; //Mark for destruction  
  232.         else  
  233.         {  
  234.             keep[i] = 1; //Mark to keep  
  235.             keepCnt += 1;  
  236.         }  
  237.     }  
  238.   
  239.     // KEEP ONLY THE GOOD  
  240.     c.t = 0;                        //Full reset on stale tracking  
  241.     // 码本时间清零  
  242.     code_element **foo = new code_element* [keepCnt];  
  243.     // 申请大小为keepCnt 的码元指针数组  
  244.     int k=0;  
  245.     for(int ii=0; ii<c.numEntries; ii++)  
  246.     {  
  247.         if(keep[ii])  
  248.         {  
  249.             foo[k] = c.cb[ii];  
  250.             foo[k]->stale = 0;       //We have to refresh these entries for next clearStale  
  251.             foo[k]->t_last_update = 0;  
  252.             k++;  
  253.         }  
  254.     }  
  255.     //CLEAN UP  
  256.     delete [] keep;  
  257.     delete [] c.cb;  
  258.     c.cb = foo;  
  259.     // 把foo 头指针地址赋给c.cb   
  260.     int numCleared = c.numEntries - keepCnt;  
  261.     // 被清理的码元个数  
  262.     c.numEntries = keepCnt;  
  263.     // 剩余的码元地址  
  264.     return(numCleared);  
  265. }  
  266.   
  267.   
  268.   
  269. int main()  
  270. {  
  271.     ///////////////////////////////////////  
  272.     // 需要使用的变量  
  273.     CvCapture*  capture;  
  274.     IplImage*   rawImage;  
  275.     IplImage*   yuvImage;  
  276.     IplImage*   ImaskCodeBook;  
  277.     codeBook*   cB;  
  278.     unsigned    cbBounds[CHANNELS];  
  279.     uchar*      pColor; //YUV pointer  
  280.     int         imageLen;  
  281.     int         nChannels = CHANNELS;  
  282.     int         minMod[CHANNELS];  
  283.     int         maxMod[CHANNELS];  
  284.       
  285.     //////////////////////////////////////////////////////////////////////////  
  286.     // 初始化各变量  
  287.     cvNamedWindow("Raw");  
  288.     cvNamedWindow("CodeBook");  
  289.   
  290.     capture = cvCreateFileCapture("tree.avi");  
  291.     if (!capture)  
  292.     {  
  293.         printf("Couldn't open the capture!");  
  294.         return -1;  
  295.     }  
  296.   
  297.     rawImage = cvQueryFrame(capture);  
  298.     yuvImage = cvCreateImage(cvGetSize(rawImage), 8, 3);      
  299.     // 给yuvImage 分配一个和rawImage 尺寸相同,8位3通道图像  
  300.     ImaskCodeBook = cvCreateImage(cvGetSize(rawImage), IPL_DEPTH_8U, 1);  
  301.     // 为ImaskCodeBook 分配一个和rawImage 尺寸相同,8位单通道图像  
  302.     cvSet(ImaskCodeBook, cvScalar(255));  
  303.     // 设置单通道数组所有元素为255,即初始化为白色图像  
  304.       
  305.     imageLen = rawImage->width * rawImage->height;  
  306.     cB = new codeBook[imageLen];  
  307.     // 得到与图像像素数目长度一样的一组码本,以便对每个像素进行处理  
  308.       
  309.     for (int i=0; i<imageLen; i++)  
  310.         // 初始化每个码元数目为0  
  311.         cB[i].numEntries = 0;  
  312.     for (int i=0; i<nChannels; i++)  
  313.     {  
  314.         cbBounds[i] = 10;   // 用于确定码元各通道的阀值  
  315.   
  316.         minMod[i]   = 20;   // 用于背景差分函数中  
  317.         maxMod[i]   = 20;   // 调整其值以达到最好的分割  
  318.     }  
  319.           
  320.       
  321.     //////////////////////////////////////////////////////////////////////////  
  322.     // 开始处理视频每一帧图像  
  323.     for (int i=0;;i++)  
  324.     {  
  325.         cvCvtColor(rawImage, yuvImage, CV_BGR2YCrCb);  
  326.         // 色彩空间转换,将rawImage 转换到YUV色彩空间,输出到yuvImage  
  327.         // 即使不转换效果依然很好  
  328.         // yuvImage = cvCloneImage(rawImage);  
  329.   
  330.         if (i <= 30)  
  331.             // 30帧内进行背景学习  
  332.         {  
  333.             pColor = (uchar *)(yuvImage->imageData);  
  334.             // 指向yuvImage 图像的通道数据  
  335.             for (int c=0; c<imageLen; c++)  
  336.             {  
  337.                 cvupdateCodeBook(pColor, cB[c], cbBounds, nChannels);  
  338.                 // 对每个像素,调用此函数,捕捉背景中相关变化图像  
  339.                 pColor += 3;  
  340.                 // 3 通道图像, 指向下一个像素通道数据  
  341.             }  
  342.             if (i == 30)  
  343.                 // 到30 帧时调用下面函数,删除码本中陈旧的码元  
  344.             {  
  345.                 for (int c=0; c<imageLen; c++)  
  346.                     cvclearStaleEntries(cB[c]);  
  347.             }  
  348.         }  
  349.         else  
  350.         {  
  351.             uchar maskPixelCodeBook;  
  352.             pColor = (uchar *)((yuvImage)->imageData); //3 channel yuv image  
  353.             uchar *pMask = (uchar *)((ImaskCodeBook)->imageData); //1 channel image  
  354.             // 指向ImaskCodeBook 通道数据序列的首元素  
  355.             for(int c=0; c<imageLen; c++)  
  356.             {  
  357.                 maskPixelCodeBook = cvbackgroundDiff(pColor, cB[c], nChannels, minMod, maxMod);  
  358.                 // 我看到这儿时豁然开朗,开始理解了codeBook 呵呵  
  359.                 *pMask++ = maskPixelCodeBook;  
  360.                 pColor += 3;  
  361.                 // pColor 指向的是3通道图像  
  362.             }  
  363.         }  
  364.         if (!(rawImage = cvQueryFrame(capture)))  
  365.             break;  
  366.         cvShowImage("Raw", rawImage);  
  367.         cvShowImage("CodeBook", ImaskCodeBook);  
  368.   
  369.         if (cvWaitKey(30) == 27)  
  370.             break;  
  371.         if (i == 56 || i == 63)  
  372.             cvWaitKey();  
  373.     }     
  374.       
  375.     cvReleaseCapture(&capture);  
  376.     if (yuvImage)  
  377.         cvReleaseImage(&yuvImage);  
  378.     if(ImaskCodeBook)   
  379.         cvReleaseImage(&ImaskCodeBook);  
  380.     cvDestroyAllWindows();  
  381.     delete [] cB;  
  382.   
  383.     return 0;  
  384. }  

56帧时

63帧时


/**
比平均背景法性能更加良好的方法,codeBook模型实现背景减除

核心代码详细解析和实现 by zcube
*/

[cpp] view plain copy
  1. /************************************************************************/  
  2. /*          A few more thoughts on codebook models 
  3. In general, the codebook method works quite well across a wide number of conditions,  
  4. and it is relatively quick to train and to run. It doesn’t deal well with varying patterns of  
  5. light — such as morning, noon, and evening sunshine — or with someone turning lights  
  6. on or off indoors. This type of global variability can be taken into account by using  
  7. several different codebook models, one for each condition, and then allowing the condition  
  8. to control which model is active.                                       */  
  9. /************************************************************************/  
  10.   
  11. #include "stdafx.h"  
  12. #include <cv.h>             
  13. #include <highgui.h>  
  14. #include <cxcore.h>  
  15.   
  16. #define CHANNELS 3        
  17. // 设置处理的图像通道数,要求小于等于图像本身的通道数  
  18.   
  19. ///////////////////////////////////////////////////////////////////////////  
  20. // 下面为码本码元的数据结构  
  21. // 处理图像时每个像素对应一个码本,每个码本中可有若干个码元  
  22. // 当涉及一个新领域,通常会遇到一些奇怪的名词,不要被这些名词吓坏,其实思路都是简单的  
  23. typedef struct ce {  
  24.     uchar   learnHigh[CHANNELS];    // High side threshold for learning  
  25.     // 此码元各通道的阀值上限(学习界限)  
  26.     uchar   learnLow[CHANNELS];     // Low side threshold for learning  
  27.     // 此码元各通道的阀值下限  
  28.     // 学习过程中如果一个新像素各通道值x[i],均有 learnLow[i]<=x[i]<=learnHigh[i],则该像素可合并于此码元  
  29.     uchar   max[CHANNELS];          // High side of box boundary  
  30.     // 属于此码元的像素中各通道的最大值  
  31.     uchar   min[CHANNELS];          // Low side of box boundary  
  32.     // 属于此码元的像素中各通道的最小值  
  33.     int     t_last_update;          // This is book keeping to allow us to kill stale entries  
  34.     // 此码元最后一次更新的时间,每一帧为一个单位时间,用于计算stale  
  35.     int     stale;                  // max negative run (biggest period of inactivity)  
  36.     // 此码元最长不更新时间,用于删除规定时间不更新的码元,精简码本  
  37. } code_element;                     // 码元的数据结构  
  38.   
  39. typedef struct code_book {  
  40.     code_element    **cb;  
  41.     // 码元的二维指针,理解为指向码元指针数组的指针,使得添加码元时不需要来回复制码元,只需要简单的指针赋值即可  
  42.     int             numEntries;  
  43.     // 此码本中码元的数目  
  44.     int             t;              // count every access  
  45.     // 此码本现在的时间,一帧为一个时间单位  
  46. } codeBook;                         // 码本的数据结构  
  47.   
  48.   
  49. ///////////////////////////////////////////////////////////////////////////////////  
  50. // int updateCodeBook(uchar *p, codeBook &c, unsigned cbBounds)  
  51. // Updates the codebook entry with a new data point  
  52. //  
  53. // p            Pointer to a YUV pixel  
  54. // c            Codebook for this pixel  
  55. // cbBounds     Learning bounds for codebook (Rule of thumb: 10)  
  56. // numChannels  Number of color channels we're learning  
  57. //  
  58. // NOTES:  
  59. //      cvBounds must be of size cvBounds[numChannels]  
  60. //  
  61. // RETURN  
  62. //  codebook index  
  63. int cvupdateCodeBook(uchar *p, codeBook &c, unsigned *cbBounds, int numChannels)  
  64. {  
  65.     if(c.numEntries == 0) c.t = 0;  
  66.     // 码本中码元为零时初始化时间为0  
  67.     c.t += 1;   // Record learning event  
  68.     // 每调用一次加一,即每一帧图像加一  
  69.       
  70.     //SET HIGH AND LOW BOUNDS  
  71.     int n;  
  72.     unsigned int high[3],low[3];  
  73.     for (n=0; n<numChannels; n++)  
  74.     {  
  75.         high[n] = *(p+n) + *(cbBounds+n);  
  76.         // *(p+n) 和 p[n] 结果等价,经试验*(p+n) 速度更快  
  77.         if(high[n] > 255) high[n] = 255;  
  78.         low[n] = *(p+n)-*(cbBounds+n);  
  79.         if(low[n] < 0) low[n] = 0;  
  80.         // 用p 所指像素通道数据,加减cbBonds中数值,作为此像素阀值的上下限  
  81.     }  
  82.   
  83.     //SEE IF THIS FITS AN EXISTING CODEWORD  
  84.     int matchChannel;     
  85.     int i;  
  86.     for (i=0; i<c.numEntries; i++)  
  87.     {  
  88.         // 遍历此码本每个码元,测试p像素是否满足其中之一  
  89.         matchChannel = 0;  
  90.         for (n=0; n<numChannels; n++)  
  91.             //遍历每个通道  
  92.         {  
  93.             if((c.cb[i]->learnLow[n] <= *(p+n)) && (*(p+n) <= c.cb[i]->learnHigh[n])) //Found an entry for this channel  
  94.             // 如果p 像素通道数据在该码元阀值上下限之间  
  95.             {     
  96.                 matchChannel++;  
  97.             }  
  98.         }  
  99.         if (matchChannel == numChannels)        // If an entry was found over all channels  
  100.             // 如果p 像素各通道都满足上面条件  
  101.         {  
  102.             c.cb[i]->t_last_update = c.t;  
  103.             // 更新该码元时间为当前时间  
  104.             // adjust this codeword for the first channel  
  105.             for (n=0; n<numChannels; n++)  
  106.                 //调整该码元各通道最大最小值  
  107.             {  
  108.                 if (c.cb[i]->max[n] < *(p+n))  
  109.                     c.cb[i]->max[n] = *(p+n);  
  110.                 else if (c.cb[i]->min[n] > *(p+n))  
  111.                     c.cb[i]->min[n] = *(p+n);  
  112.             }  
  113.             break;  
  114.         }  
  115.     }  
  116.   
  117.     // ENTER A NEW CODE WORD IF NEEDED  
  118.     if(i == c.numEntries)  // No existing code word found, make a new one  
  119.     // p 像素不满足此码本中任何一个码元,下面创建一个新码元  
  120.     {  
  121.         code_element **foo = new code_element* [c.numEntries+1];  
  122.         // 申请c.numEntries+1 个指向码元的指针  
  123.         for(int ii=0; ii<c.numEntries; ii++)  
  124.             // 将前c.numEntries 个指针指向已存在的每个码元  
  125.             foo[ii] = c.cb[ii];  
  126.           
  127.         foo[c.numEntries] = new code_element;  
  128.         // 申请一个新的码元  
  129.         if(c.numEntries) delete [] c.cb;  
  130.         // 删除c.cb 指针数组  
  131.         c.cb = foo;  
  132.         // 把foo 头指针赋给c.cb  
  133.         for(n=0; n<numChannels; n++)  
  134.             // 更新新码元各通道数据  
  135.         {  
  136.             c.cb[c.numEntries]->learnHigh[n] = high[n];  
  137.             c.cb[c.numEntries]->learnLow[n] = low[n];  
  138.             c.cb[c.numEntries]->max[n] = *(p+n);  
  139.             c.cb[c.numEntries]->min[n] = *(p+n);  
  140.         }  
  141.         c.cb[c.numEntries]->t_last_update = c.t;  
  142.         c.cb[c.numEntries]->stale = 0;  
  143.         c.numEntries += 1;  
  144.     }  
  145.   
  146.     // OVERHEAD TO TRACK POTENTIAL STALE ENTRIES  
  147.     for(int s=0; s<c.numEntries; s++)  
  148.     {  
  149.         // This garbage is to track which codebook entries are going stale  
  150.         int negRun = c.t - c.cb[s]->t_last_update;  
  151.         // 计算该码元的不更新时间  
  152.         if(c.cb[s]->stale < negRun)   
  153.             c.cb[s]->stale = negRun;  
  154.     }  
  155.   
  156.     // SLOWLY ADJUST LEARNING BOUNDS  
  157.     for(n=0; n<numChannels; n++)  
  158.         // 如果像素通道数据在高低阀值范围内,但在码元阀值之外,则缓慢调整此码元学习界限  
  159.     {  
  160.         if(c.cb[i]->learnHigh[n] < high[n])   
  161.             c.cb[i]->learnHigh[n] += 1;  
  162.         if(c.cb[i]->learnLow[n] > low[n])   
  163.             c.cb[i]->learnLow[n] -= 1;  
  164.     }  
  165.   
  166.     return(i);  
  167. }  
  168.   
  169. ///////////////////////////////////////////////////////////////////////////////////  
  170. // uchar cvbackgroundDiff(uchar *p, codeBook &c, int minMod, int maxMod)  
  171. // Given a pixel and a code book, determine if the pixel is covered by the codebook  
  172. //  
  173. // p        pixel pointer (YUV interleaved)  
  174. // c        codebook reference  
  175. // numChannels  Number of channels we are testing  
  176. // maxMod   Add this (possibly negative) number onto max level when code_element determining if new pixel is foreground  
  177. // minMod   Subract this (possible negative) number from min level code_element when determining if pixel is foreground  
  178. //  
  179. // NOTES:  
  180. // minMod and maxMod must have length numChannels, e.g. 3 channels => minMod[3], maxMod[3].  
  181. //  
  182. // Return  
  183. // 0 => background, 255 => foreground  
  184. uchar cvbackgroundDiff(uchar *p, codeBook &c, int numChannels, int *minMod, int *maxMod)  
  185. {  
  186.     // 下面步骤和背景学习中查找码元如出一辙  
  187.     int matchChannel;  
  188.     //SEE IF THIS FITS AN EXISTING CODEWORD  
  189.     int i;  
  190.     for (i=0; i<c.numEntries; i++)  
  191.     {  
  192.         matchChannel = 0;  
  193.         for (int n=0; n<numChannels; n++)  
  194.         {  
  195.             if ((c.cb[i]->min[n] - minMod[n] <= *(p+n)) && (*(p+n) <= c.cb[i]->max[n] + maxMod[n]))  
  196.                 matchChannel++; //Found an entry for this channel  
  197.             else  
  198.                 break;  
  199.         }  
  200.         if (matchChannel == numChannels)  
  201.             break//Found an entry that matched all channels  
  202.     }  
  203.     if(i == c.numEntries)   
  204.         // p像素各通道值满足码本中其中一个码元,则返回白色  
  205.         return(255);  
  206.   
  207.     return(0);  
  208. }  
  209.   
  210.   
  211. //UTILITES/////////////////////////////////////////////////////////////////////////////////////  
  212. /////////////////////////////////////////////////////////////////////////////////  
  213. //int clearStaleEntries(codeBook &c)  
  214. // After you've learned for some period of time, periodically call this to clear out stale codebook entries  
  215. //  
  216. //c     Codebook to clean up  
  217. //  
  218. // Return  
  219. // number of entries cleared  
  220. int cvclearStaleEntries(codeBook &c)  
  221. {  
  222.     int staleThresh = c.t >> 1;           // 设定刷新时间  
  223.     int *keep = new int [c.numEntries]; // 申请一个标记数组  
  224.     int keepCnt = 0;                    // 记录不删除码元数目  
  225.     //SEE WHICH CODEBOOK ENTRIES ARE TOO STALE  
  226.     for (int i=0; i<c.numEntries; i++)  
  227.         // 遍历码本中每个码元  
  228.     {  
  229.         if (c.cb[i]->stale > staleThresh)   
  230.             // 如码元中的不更新时间大于设定的刷新时间,则标记为删除  
  231.             keep[i] = 0; //Mark for destruction  
  232.         else  
  233.         {  
  234.             keep[i] = 1; //Mark to keep  
  235.             keepCnt += 1;  
  236.         }  
  237.     }  
  238.   
  239.     // KEEP ONLY THE GOOD  
  240.     c.t = 0;                        //Full reset on stale tracking  
  241.     // 码本时间清零  
  242.     code_element **foo = new code_element* [keepCnt];  
  243.     // 申请大小为keepCnt 的码元指针数组  
  244.     int k=0;  
  245.     for(int ii=0; ii<c.numEntries; ii++)  
  246.     {  
  247.         if(keep[ii])  
  248.         {  
  249.             foo[k] = c.cb[ii];  
  250.             foo[k]->stale = 0;       //We have to refresh these entries for next clearStale  
  251.             foo[k]->t_last_update = 0;  
  252.             k++;  
  253.         }  
  254.     }  
  255.     //CLEAN UP  
  256.     delete [] keep;  
  257.     delete [] c.cb;  
  258.     c.cb = foo;  
  259.     // 把foo 头指针地址赋给c.cb   
  260.     int numCleared = c.numEntries - keepCnt;  
  261.     // 被清理的码元个数  
  262.     c.numEntries = keepCnt;  
  263.     // 剩余的码元地址  
  264.     return(numCleared);  
  265. }  
  266.   
  267.   
  268.   
  269. int main()  
  270. {  
  271.     ///////////////////////////////////////  
  272.     // 需要使用的变量  
  273.     CvCapture*  capture;  
  274.     IplImage*   rawImage;  
  275.     IplImage*   yuvImage;  
  276.     IplImage*   ImaskCodeBook;  
  277.     codeBook*   cB;  
  278.     unsigned    cbBounds[CHANNELS];  
  279.     uchar*      pColor; //YUV pointer  
  280.     int         imageLen;  
  281.     int         nChannels = CHANNELS;  
  282.     int         minMod[CHANNELS];  
  283.     int         maxMod[CHANNELS];  
  284.       
  285.     //////////////////////////////////////////////////////////////////////////  
  286.     // 初始化各变量  
  287.     cvNamedWindow("Raw");  
  288.     cvNamedWindow("CodeBook");  
  289.   
  290.     capture = cvCreateFileCapture("tree.avi");  
  291.     if (!capture)  
  292.     {  
  293.         printf("Couldn't open the capture!");  
  294.         return -1;  
  295.     }  
  296.   
  297.     rawImage = cvQueryFrame(capture);  
  298.     yuvImage = cvCreateImage(cvGetSize(rawImage), 8, 3);      
  299.     // 给yuvImage 分配一个和rawImage 尺寸相同,8位3通道图像  
  300.     ImaskCodeBook = cvCreateImage(cvGetSize(rawImage), IPL_DEPTH_8U, 1);  
  301.     // 为ImaskCodeBook 分配一个和rawImage 尺寸相同,8位单通道图像  
  302.     cvSet(ImaskCodeBook, cvScalar(255));  
  303.     // 设置单通道数组所有元素为255,即初始化为白色图像  
  304.       
  305.     imageLen = rawImage->width * rawImage->height;  
  306.     cB = new codeBook[imageLen];  
  307.     // 得到与图像像素数目长度一样的一组码本,以便对每个像素进行处理  
  308.       
  309.     for (int i=0; i<imageLen; i++)  
  310.         // 初始化每个码元数目为0  
  311.         cB[i].numEntries = 0;  
  312.     for (int i=0; i<nChannels; i++)  
  313.     {  
  314.         cbBounds[i] = 10;   // 用于确定码元各通道的阀值  
  315.   
  316.         minMod[i]   = 20;   // 用于背景差分函数中  
  317.         maxMod[i]   = 20;   // 调整其值以达到最好的分割  
  318.     }  
  319.           
  320.       
  321.     //////////////////////////////////////////////////////////////////////////  
  322.     // 开始处理视频每一帧图像  
  323.     for (int i=0;;i++)  
  324.     {  
  325.         cvCvtColor(rawImage, yuvImage, CV_BGR2YCrCb);  
  326.         // 色彩空间转换,将rawImage 转换到YUV色彩空间,输出到yuvImage  
  327.         // 即使不转换效果依然很好  
  328.         // yuvImage = cvCloneImage(rawImage);  
  329.   
  330.         if (i <= 30)  
  331.             // 30帧内进行背景学习  
  332.         {  
  333.             pColor = (uchar *)(yuvImage->imageData);  
  334.             // 指向yuvImage 图像的通道数据  
  335.             for (int c=0; c<imageLen; c++)  
  336.             {  
  337.                 cvupdateCodeBook(pColor, cB[c], cbBounds, nChannels);  
  338.                 // 对每个像素,调用此函数,捕捉背景中相关变化图像  
  339.                 pColor += 3;  
  340.                 // 3 通道图像, 指向下一个像素通道数据  
  341.             }  
  342.             if (i == 30)  
  343.                 // 到30 帧时调用下面函数,删除码本中陈旧的码元  
  344.             {  
  345.                 for (int c=0; c<imageLen; c++)  
  346.                     cvclearStaleEntries(cB[c]);  
  347.             }  
  348.         }  
  349.         else  
  350.         {  
  351.             uchar maskPixelCodeBook;  
  352.             pColor = (uchar *)((yuvImage)->imageData); //3 channel yuv image  
  353.             uchar *pMask = (uchar *)((ImaskCodeBook)->imageData); //1 channel image  
  354.             // 指向ImaskCodeBook 通道数据序列的首元素  
  355.             for(int c=0; c<imageLen; c++)  
  356.             {  
  357.                 maskPixelCodeBook = cvbackgroundDiff(pColor, cB[c], nChannels, minMod, maxMod);  
  358.                 // 我看到这儿时豁然开朗,开始理解了codeBook 呵呵  
  359.                 *pMask++ = maskPixelCodeBook;  
  360.                 pColor += 3;  
  361.                 // pColor 指向的是3通道图像  
  362.             }  
  363.         }  
  364.         if (!(rawImage = cvQueryFrame(capture)))  
  365.             break;  
  366.         cvShowImage("Raw", rawImage);  
  367.         cvShowImage("CodeBook", ImaskCodeBook);  
  368.   
  369.         if (cvWaitKey(30) == 27)  
  370.             break;  
  371.         if (i == 56 || i == 63)  
  372.             cvWaitKey();  
  373.     }     
  374.       
  375.     cvReleaseCapture(&capture);  
  376.     if (yuvImage)  
  377.         cvReleaseImage(&yuvImage);  
  378.     if(ImaskCodeBook)   
  379.         cvReleaseImage(&ImaskCodeBook);  
  380.     cvDestroyAllWindows();  
  381.     delete [] cB;  
  382.   
  383.     return 0;  
  384. }  

0 0
原创粉丝点击