背景建模或前景检测(Background Generation And Foreground Detection) 三

转自:http://www.cnblogs.com/xrwang/archive/2010/04/12/BackgroundGenerationAndForegroundDetectionPhase3.html

作者:王先荣

    在上一篇文章里,我尝试翻译了《Nonparametric Background Generation》,本文主要介绍以下内容:如何实现该论文的算法,如果利用该算法来进行背景建模及前景检测,最后谈谈我的一些体会。为了使描述更加简便,以下将该论文的算法及实现称为NBGModel。

背景建模或前景检测(Background Generation And Foreground Detection) 二(非参数背景生成)的实现代码
1 使用示例
    NBGModel在使用上非常的简便,您可以仿照下面的代码来使用它:

[cpp]  view plain  copy
 print ?
  1. //初始化NBGModel对象  
  2. NBGModel nbgModel = new NBGModel(320, 240);  
  3. //训练背景模型  
  4. nbgModel.TrainBackgroundModel(historyImages);  
  5. //前景检测  
  6. nbgModel.Update(currentFrame);  
  7. //利用结果  
  8. pbResult.Image = nbgModel.ForegroundMask.Bitmap;  
  9. //释放对象  
  10. nbgModel.Dispose();  


下面是更加完整的示例:

[cpp]  view plain  copy
 print ?
  1. 更加完整的示例  
  2.   
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.ComponentModel;  
  6. using System.Data;  
  7. using System.Drawing;  
  8. using System.Linq;  
  9. using System.Text;  
  10. using System.Windows.Forms;  
  11. using System.Drawing.Imaging;  
  12. using System.Diagnostics;  
  13. using System.Runtime.InteropServices;  
  14. using Emgu.CV;  
  15. using Emgu.CV.Structure;  
  16. using Emgu.CV.CvEnum;  
  17. using System.Threading;  
  18.   
  19. namespace ImageProcessLearn  
  20. {  
  21.     public partial class FormForegroundDetect2 : Form  
  22.     {  
  23.         //成员变量  
  24.         //public const string ImageFilePathName = @"D:\Users\xrwang\Desktop\背景建模与前景检测\PETS2009\Crowd_PETS09\S0\City_Center\Time_12-34\View_001\frame_{0:D4}.jpg";  
  25.         public const string ImageFilePathName = @"E:\PETS2009\S0_City_Center\Time_12-34\View_002\frame_{0:D4}.jpg"//图像文件的路径信息,其中的{xxx}部分需要被实际的索引数字替换  
  26.         public const int ImageWidth = 768;                  //图像的宽度  
  27.         public const int ImageHeight = 576;                 //图像的高度  
  28.         public const int MaxImageFileIndexNumber = 794;     //最大的图像索引数字  
  29.         private Action action = Action.Stop;                //当前正在执行的动作  
  30.         private NBGModel nbgModel = null;                   //非参数背景模型  
  31.         private Thread threadTrainingBackground = null;     //用于训练背景的工作线程  
  32.         private Thread threadForegroundDetection = null;    //用于前景检测的工作线程  
  33.   
  34.         public FormForegroundDetect2()  
  35.         {  
  36.             InitializeComponent();  
  37.         }  
  38.   
  39.         //开始训练背景  
  40.         private void btnStartTrainingBackground_Click(object sender, EventArgs e)  
  41.         {  
  42.             threadTrainingBackground = new Thread(new ThreadStart(TrainingBackground));  
  43.             threadTrainingBackground.Start();  
  44.             action = Action.StartTrainingBackground;  
  45.             SetButtonState();  
  46.         }  
  47.   
  48.         //训练背景  
  49.         private void TrainingBackground()  
  50.         {  
  51.             //构造非参数背景模型对象  
  52.             if (nbgModel != null)  
  53.                 nbgModel.Dispose();  
  54.             NBGParameter param = (NBGParameter)this.Invoke(new GetNBGParameterDelegate(GetNBGParameter));  
  55.             nbgModel = new NBGModel(ImageWidth, ImageHeight, param);              
  56.             //添加用于训练的图像  
  57.             for (int idx = 0; idx < param.n; idx++)  
  58.             {  
  59.                 if (action != Action.StartTrainingBackground)  
  60.                     return;  
  61.                 Image<Bgr, Byte> image = new Image<Bgr, byte>(string.Format(ImageFilePathName, idx));  
  62.                 nbgModel.AddHistoryImage(image);  
  63.                 this.Invoke(new ShowTrainingBackgroundImageDelegate(ShowTrainingBackgroundImage),  
  64.                     new object[] { image.Bitmap, idx });  
  65.                 image.Dispose();  
  66.             }  
  67.             //训练背景  
  68.             Stopwatch sw = new Stopwatch();  
  69.             sw.Start();  
  70.             nbgModel.TrainBackgroundModel();  
  71.             sw.Stop();  
  72.             //显示结果  
  73.             this.Invoke(new ShowTrainingBackgroundResultDelegate(ShowTrainingBackgroundResult),  
  74.                 new object[]{ nbgModel.Mrbm.Bitmap,string.Format("NBGModel训练背景用时{0:F04}毫秒,参数(样本数目:{1},典型点数目:{2})。",sw.ElapsedMilliseconds,param.n,param.m)});  
  75.         }  
  76.   
  77.         //用于在训练背景工作线程中获取设置参数的委托及方法  
  78.         private delegate NBGParameter GetNBGParameterDelegate();  
  79.         private NBGParameter GetNBGParameter()  
  80.         {  
  81.             return new NBGParameter((int)nudNBGModelN.Value, (int)nudNBGModelM.Value, (double)nudNBGModelTheta.Value, (double)nudNBGModelT.Value, new MCvTermCriteria((int)nudNBGModelMaxIter.Value, (double)nudNBGModelEps.Value));  
  82.         }  
  83.   
  84.         //用于在训练背景工作线程中显示结果的委托及方法  
  85.         private delegate void ShowTrainingBackgroundResultDelegate(Bitmap mrbm, string result);  
  86.         private void ShowTrainingBackgroundResult(Bitmap mrbm, string result)  
  87.         {  
  88.             pbResult.Image = mrbm;  
  89.             txtResult.Text += result + "\r\n";  
  90.             action = Action.Stop;  
  91.             SetButtonState();  
  92.         }  
  93.   
  94.         //用于在训练背景工作线程中显示训练图像的委托及方法  
  95.         private delegate void ShowTrainingBackgroundImageDelegate(Bitmap bitmap, int idx);  
  96.         private void ShowTrainingBackgroundImage(Bitmap bitmap, int idx)  
  97.         {  
  98.             pbSource.Image = bitmap;  
  99.             lblImageIndex.Text = string.Format("{0:D4}", idx);  
  100.         }  
  101.   
  102.         //开始前景检测  
  103.         private void btnStartForegroundDetection_Click(object sender, EventArgs e)  
  104.         {  
  105.             threadForegroundDetection = new Thread(new ThreadStart(ForegroundDetection));  
  106.             threadForegroundDetection.Start();  
  107.             action = Action.StartForegroundDetection;  
  108.             SetButtonState();  
  109.         }  
  110.   
  111.         //检测前景  
  112.         private void ForegroundDetection()  
  113.         {  
  114.             if (nbgModel == null)  
  115.                 return;  
  116.             Stopwatch sw = new Stopwatch();  
  117.             int idx;  
  118.             for (idx = nbgModel.Param.n; idx < MaxImageFileIndexNumber; idx++)  
  119.             {  
  120.                 if (action != Action.StartForegroundDetection)  
  121.                     break;  
  122.                 if ((idx - nbgModel.Param.n) % 50 == 49)  
  123.                     nbgModel.ClearStale(40);  
  124.                 Image<Bgr, Byte> image = new Image<Bgr, byte>(string.Format(ImageFilePathName, idx));  
  125.                 sw.Start();  
  126.                 nbgModel.Update(image);  
  127.                 sw.Stop();  
  128.                 Image<Bgr, Byte> imageForground = image.Copy(nbgModel.ForegroundMask);  
  129.                 this.Invoke(new ShowForegroundDetectionImageDelegate(ShowForegroundDetectionImage),  
  130.                     new object[] { image.Bitmap, imageForground.Bitmap, idx });  
  131.                 image.Dispose();  
  132.                 imageForground.Dispose();  
  133.             }  
  134.             int frames = idx - nbgModel.Param.n;  
  135.             this.Invoke(new ShowForegroundDetectionResultDelegate(ShowForegroundDetectionResult),  
  136.                 new object[] { string.Format("NBGModel前景检测,共{0}帧,平均耗时{1:F04}毫秒,参数(样本数目:{2},典型点数目:{3},权重系数:{4},最小差值:{5},最大迭代次数:{6},终止精度:{7})",  
  137.                 frames,1d*sw.ElapsedMilliseconds/frames,nbgModel.Param.n,nbgModel.Param.m,nbgModel.Param.theta,nbgModel.Param.t,nbgModel.Param.criteria.max_iter,nbgModel.Param.criteria.epsilon)});  
  138.         }  
  139.   
  140.         //用于在前景检测工作线程中显示图像的委托及方法  
  141.         private delegate void ShowForegroundDetectionImageDelegate(Bitmap image, Bitmap foreground, int idx);  
  142.         private void ShowForegroundDetectionImage(Bitmap image, Bitmap foreground, int idx)  
  143.         {  
  144.             pbSource.Image = image;  
  145.             pbResult.Image = foreground;  
  146.             lblImageIndex.Text = string.Format("{0:D4}", idx);  
  147.         }  
  148.   
  149.         //用于在前景检测工作线程中显示结果的委托及方法  
  150.         private delegate void ShowForegroundDetectionResultDelegate(string result);  
  151.         private void ShowForegroundDetectionResult(string result)  
  152.         {  
  153.             txtResult.Text += result;  
  154.         }  
  155.   
  156.         //停止  
  157.         private void btnStop_Click(object sender, EventArgs e)  
  158.         {  
  159.             if (action == Action.StartTrainingBackground)  
  160.             {  
  161.                 action = Action.Stop;  
  162.                 Thread.Sleep(1);  
  163.                 if (threadTrainingBackground.ThreadState == System.Threading.ThreadState.Running)  
  164.                     threadTrainingBackground.Abort();  
  165.                 nbgModel.Dispose();  
  166.                 nbgModel = null;  
  167.             }  
  168.             action = Action.Stop;  
  169.             SetButtonState();  
  170.         }  
  171.   
  172.         /// <summary>  
  173.         /// 设置按钮的状态  
  174.         /// </summary>  
  175.         private void SetButtonState()  
  176.         {  
  177.             if (action == Action.Stop)  
  178.             {  
  179.                 btnStartTrainingBackground.Enabled = true;  
  180.                 btnStartForegroundDetection.Enabled = true;  
  181.                 btnStop.Enabled = false;  
  182.             }  
  183.             else if (action == Action.StartForegroundDetection || action==Action.StartTrainingBackground)  
  184.             {  
  185.                 btnStartTrainingBackground.Enabled = false;  
  186.                 btnStartForegroundDetection.Enabled = false;  
  187.                 btnStop.Enabled = true;  
  188.             }  
  189.         }  
  190.   
  191.         //加载窗体时  
  192.         private void FormForegroundDetect2_Load(object sender, EventArgs e)  
  193.         {  
  194.             toolTip.SetToolTip(nudNBGModelN, "样本数目:需要被保存的历史图像数目");  
  195.             toolTip.SetToolTip(nudNBGModelM, "典型点数目:历史图像需要被分为多少组");  
  196.             toolTip.SetToolTip(nudNBGModelTheta, "权重系数:权重大于该值的聚集中心是候选背景");  
  197.             toolTip.SetToolTip(nudNBGModelT, "最小差值:观测值与聚集中心的最小差值如果大于该值,为前景;否则为背景");  
  198.             toolTip.SetToolTip(nudNBGModelMaxIter, "最大迭代次数:MeanShift计算过程中的最大迭代次数");  
  199.             toolTip.SetToolTip(nudNBGModelEps, "终止精度:MeanShift计算过程中,如果矩形窗的位移小于等于该值,则停止计算");  
  200.   
  201.             pbSource.Image = Image.FromFile(string.Format(ImageFilePathName, 0));  
  202.             lblImageIndex.Text = string.Format("{0:D4}", 0);  
  203.         }  
  204.   
  205.         //当窗体关闭后,释放资源  
  206.         private void FormForegroundDetect2_FormClosed(object sender, FormClosedEventArgs e)  
  207.         {  
  208.             if (threadTrainingBackground != null && threadTrainingBackground.ThreadState == System.Threading.ThreadState.Running)  
  209.                 threadTrainingBackground.Abort();  
  210.             if (threadForegroundDetection != null && threadForegroundDetection.ThreadState == System.Threading.ThreadState.Running)  
  211.                 threadForegroundDetection.Abort();  
  212.             if (nbgModel != null)  
  213.                 nbgModel.Dispose();  
  214.         }  
  215.     }  
  216.   
  217.     /// <summary>  
  218.     /// 当前正在执行的动作  
  219.     /// </summary>  
  220.     public enum Action  
  221.     {  
  222.         StartTrainingBackground,    //开始训练背景  
  223.         StartForegroundDetection,   //开始前景检测  
  224.         Stop                        //停止  
  225.     }  
  226. }  

2 实现NBGModel
    2.1 我在实现NBGModel的时候基本上跟论文中的方式一样,不过有以下两点区别:
(1)论文中的MeanShift计算使用了Epanechnikov核函数,我使用的是矩形窗形式的MeanShift计算。主要是因为我自己不会实现MeanShift,只能利用OpenCV中提供的cvMeanShift函数。这样做也有一个好处——不再需要计算与保存典型点。
(2)论文中的方法在检测的过程中聚集中心会不断的增加,我模仿CodeBook的实现为其增加了一个清除消极聚集中心的ClearStable方法。这样可以在必要的时候将长期不活跃的聚集中心清除掉。

    2.2 NBGModel中用到的数据成员如下所示:
        private int width;                                          //图像的宽度
        private int height;                                         //图像的高度
        private NBGParameter param;                                 //非参数背景模型的参数

        private List<Image<Ycc, Byte>> historyImages = null;        //历史图像:列表个数为param.n,在更新时如果个数大于等于param.n,删除最早的历史图像,加入最新的历史图像
        //由于这里采用矩形窗口方式的MeanShift计算,因此不再需要分组图像的典型点。这跟论文不一样。
        //private List<Image<Ycc,Byte>> convergenceImages = null;   //收敛图像:列表个数为param.m,仅在背景训练时使用,训练结束即被清空,因此这里不再声明
        private Image<Gray, Byte> sampleImage = null;               //样本图像:保存历史图像中每个像素在Y通道的值,用于MeanShift计算
        private List<ClusterCenter<Ycc>>[,] clusterCenters = null;  //聚集中心数据:将收敛点分类之后得到的聚集中心,数组大小为:height x width,列表元素个数不定q(q<=m)。
        private Image<Ycc, Byte> mrbm = null;                       //最可靠背景模型

        private Image<Gray, Byte> backgroundMask = null;            //背景掩码图像

        private double frameCount = 0;                              //总帧数(不包括训练阶段的帧数n)

其中,NBGParameter结构包含以下成员:
        public int n;                       //样本数目:需要被保留的历史图像数目
        public int m;                       //典型点数目:历史图像需要被分为多少组
        public double theta;                //权重系数:权重大于该值的聚集中心为候选背景
        public double t;                    //最小差值:观测值与候选背景的最小差值大于该值时,为前景;否则为背景
        public MCvTermCriteria criteria;    //Mean Shift计算的终止条件:包括最大迭代次数和终止计算的精度

聚集中心ClusterCenter使用类而不是结构,是为了方便更新,它包含以下成员:
        public TColor ci;              //聚集中心的像素值
        public double wi;              //聚集中心的权重
        public double li;              //聚集中心包含的收敛点数目
        public double updateFrameNo;   //更新该聚集中心时的帧数:用于清除消极的聚集中心

    2.3 NBGModel中的关键流程
1.背景建模
(1)将训练用的样本图像添加到历史图像historyImages中;
(2)将历史图像分为m组,以每组所在位置的矩形窗为起点进行MeanShift计算,结果窗的中点为收敛中心,收敛中心的像素值为收敛值,将收敛值添加到收敛图像convergenceImages中;
(3)计算收敛图像的聚集中心:(a)得到收敛中心的最小值Cmin;(b)将[0,Cmin+t]区间中的收敛中心划分为一类;(c)计算已分类收敛中心的平均值,作为聚集中心的值;(d)删除已分类的收敛中心;(e)重复a~d,直到收敛中心全部归类;
(4)得到最可靠背景模型MRBM:在聚集中心中选取wi最大的值作为某个像素的最可靠背景。

2.前景检测
(1)用wi≥theta作为条件选择可能的背景组Cb;
(2)对每个观测值x0,计算x0与Cb的最小差值d;
(3)如果d>t,则该点为前景;否则为背景。

3.背景维持
(1)如果某点为背景,更新最近聚集中心的wi为(li+1)/m;
(2)如果某点为前景:(a)以该点所在的矩形窗为起点进行MeanShift计算,可得到新的收敛中心Cnew(wi=1/m);(b)将Cnew加入到聚集中心clusterCenters;
(3)在必要的时候,清理消极的聚集中心。

2.4 NBGModel的实现代码
值得注意的是:在实现代码中,有好几个以2结尾的私有方法,它们主要用于演示算法流程,实际上并未使用。为了优化性能而增加了不少指针操作之后的代码可读性变得很差。

[cpp]  view plain  copy
 print ?
  1. NBGModel实现代码  
  2.   
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Drawing;  
  8. using System.Drawing.Imaging;  
  9. using System.Diagnostics;  
  10. using System.Runtime.InteropServices;  
  11. using Emgu.CV;  
  12. using Emgu.CV.Structure;  
  13. using Emgu.CV.CvEnum;  
  14.   
  15. namespace ImageProcessLearn  
  16. {  
  17.     public class NBGModel : IDisposable  
  18.     {  
  19.         //成员变量  
  20.         private int width;                                          //图像的宽度  
  21.         private int height;                                         //图像的高度  
  22.         private NBGParameter param;                                 //非参数背景模型的参数  
  23.   
  24.         private List<Image<Ycc, Byte>> historyImages = null;        //历史图像:列表个数为param.n,在更新时如果个数大于param.n,删除最早的历史图像,加入最新的历史图像  
  25.         //由于这里采用矩形窗口方式的MeanShift计算,因此不再需要分组图像的典型点。这跟论文不一样。  
  26.         //private List<Image<Ycc,Byte>> convergenceImages = null;   //收敛图像:列表个数为param.m,仅在背景训练时使用,训练结束即被清空,因此这里不再声明  
  27.         private Image<Gray, Byte> sampleImage = null;               //样本图像:保存历史图像中每个像素在Y通道的值,用于MeanShift计算  
  28.         private List<ClusterCenter<Ycc>>[,] clusterCenters = null;  //聚集中心数据:将收敛点分类之后得到的聚集中心,数组大小为:height x width,列表元素个数不定q(q<=m)。  
  29.         private Image<Ycc, Byte> mrbm = null;                       //最可靠背景模型  
  30.   
  31.         private Image<Gray, Byte> backgroundMask = null;            //背景掩码图像  
  32.   
  33.         private double frameCount = 0;                              //总帧数(不包括训练阶段的帧数n)  
  34.   
  35.         //属性  
  36.         /// <summary>  
  37.         /// 图像的宽度  
  38.         /// </summary>  
  39.         public int Width  
  40.         {  
  41.             get  
  42.             {  
  43.                 return width;  
  44.             }  
  45.         }  
  46.   
  47.         /// <summary>  
  48.         /// 图像的高度  
  49.         /// </summary>  
  50.         public int Height  
  51.         {  
  52.             get  
  53.             {  
  54.                 return height;  
  55.             }  
  56.         }  
  57.   
  58.         /// <summary>  
  59.         /// 非参数背景模型的参数  
  60.         /// </summary>  
  61.         public NBGParameter Param  
  62.         {  
  63.             get  
  64.             {  
  65.                 return param;  
  66.             }  
  67.         }  
  68.   
  69.         /// <summary>  
  70.         /// 最可靠背景模型  
  71.         /// </summary>  
  72.         public Image<Ycc, Byte> Mrbm  
  73.         {  
  74.             get  
  75.             {  
  76.                 return mrbm;  
  77.             }  
  78.         }  
  79.   
  80.         /// <summary>  
  81.         /// 背景掩码  
  82.         /// </summary>  
  83.         public Image<Gray, Byte> BackgroundMask  
  84.         {  
  85.             get  
  86.             {  
  87.                 return backgroundMask;  
  88.             }  
  89.         }  
  90.   
  91.         /// <summary>  
  92.         /// 前景掩码  
  93.         /// </summary>  
  94.         public Image<Gray, Byte> ForegroundMask  
  95.         {  
  96.             get  
  97.             {  
  98.                 return backgroundMask.Not();  
  99.             }  
  100.         }  
  101.   
  102.         /// <summary>  
  103.         /// 总帧数  
  104.         /// </summary>  
  105.         public double FrameCount  
  106.         {  
  107.             get  
  108.             {  
  109.                 return frameCount;  
  110.             }  
  111.         }  
  112.   
  113.         /// <summary>  
  114.         /// 构造函数  
  115.         /// </summary>  
  116.         /// <param name="width">图像宽度</param>  
  117.         /// <param name="height">图像高度</param>  
  118.         public NBGModel(int width, int height)  
  119.             : this(width, height, NBGParameter.GetDefaultNBGParameter())  
  120.         {  
  121.         }  
  122.   
  123.         /// <summary>  
  124.         /// 构造函数  
  125.         /// </summary>  
  126.         /// <param name="width">图像宽度</param>  
  127.         /// <param name="height">图像高度</param>  
  128.         ///<param name="param">非参数背景模型的参数</param>  
  129.         public NBGModel(int width, int height, NBGParameter param)  
  130.         {  
  131.             CheckParameters(width, height, param);  
  132.             this.width = width;  
  133.             this.height = height;  
  134.             this.param = param;  
  135.   
  136.             historyImages = new List<Image<Ycc, byte>>(param.n);  
  137.             sampleImage = new Image<Gray, byte>(param.n, 1);  
  138.             clusterCenters = new List<ClusterCenter<Ycc>>[height, width];  
  139.             for (int row = 0; row < height; row++)  
  140.             {  
  141.                 for (int col = 0; col < width; col++)  
  142.                     clusterCenters[row, col] = new List<ClusterCenter<Ycc>>(param.m);   //聚集中心列表不定长,因此将其初始化为m个元素的容量  
  143.             }  
  144.             mrbm = new Image<Ycc, byte>(width, height);  
  145.             backgroundMask = new Image<Gray, byte>(width, height);  
  146.             frameCount = 0;  
  147.         }  
  148.   
  149.         /// <summary>  
  150.         /// 检查参数是否正确,如果不正确,抛出异常  
  151.         /// </summary>  
  152.         /// <param name="width">图像宽度</param>  
  153.         /// <param name="height">图像高度</param>  
  154.         /// <param name="param">非参数背景模型的参数</param>  
  155.         private void CheckParameters(int width, int height, NBGParameter param)  
  156.         {  
  157.             if (width <= 0)  
  158.                 throw new ArgumentOutOfRangeException("width", width, "图像宽度必须大于零。");  
  159.             if (height <= 0)  
  160.                 throw new ArgumentOutOfRangeException("height", height, "图像高度必须大于零。");  
  161.             if (param.n <= 0)  
  162.                 throw new ArgumentOutOfRangeException("n", param.n, "样本数目必须大于零。");  
  163.             if (param.m <= 0)  
  164.                 throw new ArgumentOutOfRangeException("m", param.m, "典型点数目必须大于零。");  
  165.             if (param.n % param.m != 0)  
  166.                 throw new ArgumentException("样本数目必须是典型点数目的整数倍。""n,m");  
  167.             if (param.theta <= 0 || param.theta > 1)  
  168.                 throw new ArgumentOutOfRangeException("theta", param.theta, "权重系数必须大于零,并且小于1。");  
  169.             if (param.t <= 0)  
  170.                 throw new ArgumentOutOfRangeException("t", param.t, "最小差值必须大于零。");  
  171.         }  
  172.   
  173.         /// <summary>  
  174.         /// 释放资源  
  175.         /// </summary>  
  176.         public void Dispose()  
  177.         {  
  178.             if (historyImages != null && historyImages.Count > 0)  
  179.             {  
  180.                 foreach (Image<Ycc, byte> historyImage in historyImages)  
  181.                 {  
  182.                     if (historyImage != null)  
  183.                         historyImage.Dispose();  
  184.                 }  
  185.             }  
  186.             if (sampleImage != null)  
  187.                 sampleImage.Dispose();  
  188.             if (clusterCenters != null && clusterCenters.Length > 0)  
  189.             {  
  190.                 foreach (List<ClusterCenter<Ycc>> clusterCentersElement in clusterCenters)  
  191.                     clusterCentersElement.Clear();  
  192.             }  
  193.             if (mrbm != null)  
  194.                 mrbm.Dispose();  
  195.             if (backgroundMask != null)  
  196.                 backgroundMask.Dispose();  
  197.         }  
  198.   
  199.         /// <summary>  
  200.         /// 增加历史图像  
  201.         /// </summary>  
  202.         /// <param name="historyImage">历史图像</param>  
  203.         /// <returns>是否增加成功</returns>  
  204.         public bool AddHistoryImage(Image<Ycc, byte> historyImage)  
  205.         {  
  206.             bool success = false;  
  207.             if (historyImage != null && historyImage.Width == width && historyImage.Height == height)  
  208.             {  
  209.                 if (historyImages.Count >= param.n)  
  210.                 {  
  211.                     if (historyImages[0] != null)  
  212.                         historyImages[0].Dispose();  
  213.                     historyImages.RemoveAt(0);  
  214.                 }  
  215.                 historyImages.Add(historyImage.Copy());  
  216.                 success = true;  
  217.             }  
  218.             return success;  
  219.         }  
  220.   
  221.         /// <summary>  
  222.         /// 增加历史图像  
  223.         /// </summary>  
  224.         /// <param name="historyImages">历史图像数组</param>  
  225.         /// <returns>返回成功增加的历史图像数目</returns>  
  226.         public int AddHistoryImage(Image<Ycc,byte>[] historyImages)  
  227.         {  
  228.             int added = 0;  
  229.             if (historyImages != null && historyImages.Length > 0)  
  230.             {  
  231.                 foreach (Image<Ycc,byte> historyImage in historyImages)  
  232.                 {  
  233.                     if (AddHistoryImage(historyImage))  
  234.                         added++;  
  235.                 }  
  236.             }  
  237.             return added;  
  238.         }  
  239.   
  240.         /// <summary>  
  241.         /// 增加历史图像  
  242.         /// </summary>  
  243.         /// <param name="historyImages">历史图像列表</param>  
  244.         /// <returns>返回成功增加的历史图像数目</returns>  
  245.         public int AddHistoryImage(List<Image<Ycc,byte>> historyImages)  
  246.         {  
  247.             return AddHistoryImage(historyImages.ToArray());  
  248.         }  
  249.   
  250.         /// <summary>  
  251.         /// 增加历史图像  
  252.         /// </summary>  
  253.         /// <param name="historyImage">历史图像</param>  
  254.         /// <returns>是否增加成功</returns>  
  255.         public bool AddHistoryImage(Image<Bgr, byte> historyImage)  
  256.         {  
  257.             Image<Ycc, byte> image = historyImage.Convert<Ycc, byte>();  
  258.             bool success = AddHistoryImage(image);  
  259.             image.Dispose();  
  260.             return success;  
  261.         }  
  262.   
  263.         /// <summary>  
  264.         /// 增加历史图像  
  265.         /// </summary>  
  266.         /// <param name="historyImages">历史图像数组</param>  
  267.         /// <returns>返回成功增加的历史图像数目</returns>  
  268.         public int AddHistoryImage(Image<Bgr, byte>[] historyImages)  
  269.         {  
  270.             int added = 0;  
  271.             if (historyImages != null && historyImages.Length > 0)  
  272.             {  
  273.                 foreach (Image<Bgr, byte> historyImage in historyImages)  
  274.                 {  
  275.                     if (AddHistoryImage(historyImage))  
  276.                         added++;  
  277.                 }  
  278.             }  
  279.             return added;  
  280.         }  
  281.   
  282.         /// <summary>  
  283.         /// 增加历史图像  
  284.         /// </summary>  
  285.         /// <param name="historyImages">历史图像列表</param>  
  286.         /// <returns>返回成功增加的历史图像数目</returns>  
  287.         public int AddHistoryImage(List<Image<Bgr, byte>> historyImages)  
  288.         {  
  289.             return AddHistoryImage(historyImages.ToArray());  
  290.         }  
  291.   
  292.         /// <summary>  
  293.         /// 训练背景模型  
  294.         /// </summary>  
  295.         /// <returns>返回训练是否成功</returns>  
  296.         unsafe public bool TrainBackgroundModel()  
  297.         {  
  298.             bool success = false;  
  299.             if (historyImages.Count >= param.n)  
  300.             {  
  301.                 //0.初始化收敛图像,个数为param.m  
  302.                 List<Image<Ycc, byte>> convergenceImages = new List<Image<Ycc, byte>>(param.m);  
  303.                 for (int i = 0; i < param.m; i++)  
  304.                     convergenceImages.Add(new Image<Ycc, byte>(width, height));  
  305.                 //1.将历史图像分为m组,以每组的位置为矩形窗的起点,对通道Y在历史图像中进行MeanShift计算,结果窗的中点为收敛中心,该中心的值为收敛值,将收敛值加入到convergenceImageData中。  
  306.                 int numberPerGroup = param.n / param.m; //每组图像的数目  
  307.                 MCvConnectedComp comp;                                  //保存Mean Shift计算结果的连接部件  
  308.                 int offsetHistoryImage;                                                     //历史图像中某个像素相对图像数据起点的偏移量  
  309.                 int widthStepHistoryImage = historyImages[0].MIplImage.widthStep;           //历史图像的每行字节数  
  310.                 byte*[] ptrHistoryImages = new byte*[param.n];                              //历史图像的数据部分起点数组  
  311.                 byte* ptrSampleImage = (byte*)sampleImage.MIplImage.imageData.ToPointer();  //样本图像的数据部分起点  
  312.                 int offsetConvergenceImage;                                                 //收敛图像中某个像素相对图像数据起点的偏移量  
  313.                 int widthStepConvergenceImage = convergenceImages[0].MIplImage.widthStep;   //收敛图像的每行字节数  
  314.                 byte*[] ptrConvergenceImages = new byte*[param.m];                          //收敛图像的数据部分起点数组  
  315.                 for (int i = 0; i < param.n; i++)  
  316.                     ptrHistoryImages[i] = (byte*)historyImages[i].MIplImage.imageData.ToPointer();  
  317.                 for (int i = 0; i < param.m; i++)  
  318.                     ptrConvergenceImages[i] = (byte*)convergenceImages[i].MIplImage.imageData.ToPointer();  
  319.                 //遍历图像的每一行  
  320.                 for (int row = 0; row < height; row++)  
  321.                 {  
  322.                     //遍历图像的每一列  
  323.                     for (int col = 0; col < width; col++)  
  324.                     {  
  325.                         offsetHistoryImage = row * widthStepHistoryImage + col * 3;  
  326.                         offsetConvergenceImage = row * widthStepConvergenceImage + col * 3;  
  327.                         //用历史图像在该点的Y通道值组成一副用于Mean Shift计算的样本图像  
  328.                         for (int sampleIdx = 0; sampleIdx < param.n; sampleIdx++)  
  329.                             *(ptrSampleImage + sampleIdx) = *(ptrHistoryImages[sampleIdx] + offsetHistoryImage);  
  330.                         //以每组的位置为矩形窗的起点,用MeanShift过程找到局部极值,由局部极值组成的图像是收敛图像  
  331.                         for (int representativeIdx = 0; representativeIdx < param.m; representativeIdx++)  
  332.                         {  
  333.                             Rectangle window = new Rectangle(representativeIdx * numberPerGroup, 0, numberPerGroup, 1);  
  334.                             CvInvoke.cvMeanShift(sampleImage.Ptr, window, param.criteria, out comp);  
  335.                             int center = comp.rect.Left + comp.rect.Width / 2;      //收敛中心  
  336.                             *(ptrConvergenceImages[representativeIdx] + offsetConvergenceImage) = *(ptrHistoryImages[center] + offsetHistoryImage);  
  337.                             *(ptrConvergenceImages[representativeIdx] + offsetConvergenceImage + 1) = *(ptrHistoryImages[center] + offsetHistoryImage + 1);  
  338.                             *(ptrConvergenceImages[representativeIdx] + offsetConvergenceImage + 2) = *(ptrHistoryImages[center] + offsetHistoryImage + 2);  
  339.                         }  
  340.                     }  
  341.                 }  
  342.                 //2.将近似的收敛点分类,以得到聚集中心  
  343.                 //(1)得到收敛中心的最小值Cmin;(2)将[0 , Cmin+t]区间中的收敛中心划为一类;(3)计算已分类点的平均值,作为聚集中心的值,并将聚集中心添加到clusterCenters;(4)删除已分类的收敛中心;(5)重复(0)~(4)直到收敛中心全部归类。  
  344.                 for (int row = 0; row < height; row++)  
  345.                 {  
  346.                     //遍历图像的每一列  
  347.                     for (int col = 0; col < width; col++)  
  348.                     {  
  349.                         offsetConvergenceImage = row * widthStepConvergenceImage + col * 3;  
  350.                         //得到该像素的收敛中心列表  
  351.                         List<Ycc> convergenceCenters = new List<Ycc>(param.m);  
  352.                         for (int convergenceIdx = 0; convergenceIdx < param.m; convergenceIdx++)  
  353.                             convergenceCenters.Add(new Ycc(*(ptrConvergenceImages[convergenceIdx] + offsetConvergenceImage), *(ptrConvergenceImages[convergenceIdx] + offsetConvergenceImage + 1), *(ptrConvergenceImages[convergenceIdx] + offsetConvergenceImage + 2)));  
  354.                         while (convergenceCenters.Count > 0)  
  355.                         {  
  356.                             Ycc Cmin = MinYcc(convergenceCenters);  
  357.                             double regionHigh = Cmin.Y + param.t;  
  358.                             Ycc sum = new Ycc(0d, 0d, 0d);  
  359.                             double li = 0d;  
  360.                             for (int i = convergenceCenters.Count - 1; i >= 0; i--)  
  361.                             {  
  362.                                 Ycc ci = convergenceCenters[i];  
  363.                                 if (ci.Y <= regionHigh)  
  364.                                 {  
  365.                                     sum.Y += ci.Y;  
  366.                                     sum.Cr += ci.Cr;  
  367.                                     sum.Cb += ci.Cb;  
  368.                                     li++;  
  369.                                     convergenceCenters.RemoveAt(i);  
  370.                                 }  
  371.                             }  
  372.                             Ycc avg = new Ycc(sum.Y / li, sum.Cr / li, sum.Cb / li);  
  373.                             double wi = li / param.m;  
  374.                             ClusterCenter<Ycc> clusterCenter = new ClusterCenter<Ycc>(avg, wi, li, 0d);  
  375.                             clusterCenters[row, col].Add(clusterCenter);  
  376.                         }  
  377.                     }  
  378.                 }  
  379.                 //3.得到最可靠背景模型  
  380.                 GetMrbm();  
  381.                 //4.释放资源  
  382.                 for (int i = 0; i < param.m; i++)  
  383.                     convergenceImages[i].Dispose();  
  384.                 convergenceImages.Clear();  
  385.                 success = true;  
  386.             }  
  387.             return success;  
  388.         }  
  389.   
  390.         /// <summary>  
  391.         /// 训练背景模型(没有使用指针运算进行优化,用于演示流程)  
  392.         /// </summary>  
  393.         /// <returns>返回训练是否成功</returns>  
  394.         private bool TrainBackgroundModel2()  
  395.         {  
  396.             bool success = false;  
  397.             if (historyImages.Count >= param.n)  
  398.             {  
  399.                 //0.初始化收敛图像,个数为param.m  
  400.                 List<Image<Ycc, byte>> convergenceImages = new List<Image<Ycc, byte>>(param.m);  
  401.                 for (int i = 0; i < param.m; i++)  
  402.                     convergenceImages.Add(new Image<Ycc, byte>(width, height));  
  403.                 //1.将历史图像分为m组,以每组的位置为矩形窗的起点,对通道Y在历史图像中进行MeanShift计算,结果窗的中点为收敛中心,该中心的值为收敛值,将收敛值加入到convergenceImageData中。  
  404.                 int numberPerGroup = param.n / param.m; //每组图像的数目  
  405.                 MCvConnectedComp comp;                                  //保存Mean Shift计算结果的连接部件  
  406.                 //遍历图像的每一行  
  407.                 for (int row = 0; row < height; row++)  
  408.                 {  
  409.                     //遍历图像的每一列  
  410.                     for (int col = 0; col < width; col++)  
  411.                     {  
  412.                         //用历史图像在该点的Y通道值组成一副用于Mean Shift计算的样本图像  
  413.                         for (int sampleIdx = 0; sampleIdx < param.n; sampleIdx++)  
  414.                             sampleImage[0, sampleIdx] = new Gray(historyImages[sampleIdx][row, col].Y);  //这里可以用指针优化访问像素的速度  
  415.                         //以每组的位置为矩形窗的起点,用MeanShift过程找到局部极值,由局部极值组成的图像是收敛图像  
  416.                         for (int representativeIdx = 0; representativeIdx < param.m; representativeIdx++)  
  417.                         {  
  418.                             Rectangle window = new Rectangle(representativeIdx * numberPerGroup, 0, numberPerGroup, 1);  
  419.                             CvInvoke.cvMeanShift(sampleImage.Ptr, window, param.criteria, out comp);  
  420.                             int center = comp.rect.Left + comp.rect.Width / 2;      //收敛中心  
  421.                             Ycc ci = historyImages[center][row, col];               //收敛中心对应的像素值  
  422.                             convergenceImages[representativeIdx][row, col] = ci;    //将收敛中心添加到收敛图像数据中去(这两句可以用指针优化访问像素的速度)  
  423.                         }  
  424.                     }  
  425.                 }  
  426.                 //2.将近似的收敛点分类,以得到聚集中心  
  427.                 //(1)得到收敛中心的最小值Cmin;(2)将[0 , Cmin+t]区间中的收敛中心划为一类;(3)计算已分类点的平均值,作为聚集中心的值,并将聚集中心添加到clusterCenters;(4)删除已分类的收敛中心;(5)重复(0)~(4)直到收敛中心全部归类。  
  428.                 for (int row = 0; row < height; row++)  
  429.                 {  
  430.                     //遍历图像的每一列  
  431.                     for (int col = 0; col < width; col++)  
  432.                     {  
  433.                         //得到该像素的收敛中心列表  
  434.                         List<Ycc> convergenceCenters = new List<Ycc>(param.m);  
  435.                         for (int convergenceIdx = 0; convergenceIdx < param.m; convergenceIdx++)  
  436.                             convergenceCenters.Add(convergenceImages[convergenceIdx][row, col]);  
  437.                         while (convergenceCenters.Count > 0)  
  438.                         {  
  439.                             Ycc Cmin = MinYcc(convergenceCenters);  
  440.                             double regionHigh = Cmin.Y + param.t;  
  441.                             Ycc sum = new Ycc(0d, 0d, 0d);  
  442.                             double li = 0d;  
  443.                             for (int i = convergenceCenters.Count - 1; i >= 0; i--)  
  444.                             {  
  445.                                 Ycc ci = convergenceCenters[i];  
  446.                                 if (ci.Y <= regionHigh)  
  447.                                 {  
  448.                                     sum.Y += ci.Y;  
  449.                                     sum.Cr += ci.Cr;  
  450.                                     sum.Cb += ci.Cb;  
  451.                                     li++;  
  452.                                     convergenceCenters.RemoveAt(i);  
  453.                                 }  
  454.                             }  
  455.                             Ycc avg = new Ycc(sum.Y / li, sum.Cr / li, sum.Cb / li);  
  456.                             double wi = li / param.m;  
  457.                             ClusterCenter<Ycc> clusterCenter = new ClusterCenter<Ycc>(avg, wi, li, 0d);  
  458.                             clusterCenters[row, col].Add(clusterCenter);  
  459.                         }  
  460.                     }  
  461.                 }  
  462.                 //3.得到最可靠背景模型  
  463.                 GetMrbm();  
  464.                 //4.释放资源  
  465.                 for (int i = 0; i < param.m; i++)  
  466.                     convergenceImages[i].Dispose();  
  467.                 convergenceImages.Clear();  
  468.                 success = true;  
  469.             }  
  470.             return success;  
  471.         }  
  472.   
  473.         /// <summary>  
  474.         /// 训练背景模型  
  475.         /// </summary>  
  476.         /// <param name="historyImages">历史图像数组</param>  
  477.         /// <returns>返回训练是否成功</returns>  
  478.         public bool TrainBackgroundModel(Image<Ycc,byte>[] historyImages)  
  479.         {  
  480.             AddHistoryImage(historyImages);  
  481.             return TrainBackgroundModel();  
  482.         }  
  483.   
  484.         /// <summary>  
  485.         /// 训练背景模型  
  486.         /// </summary>  
  487.         /// <param name="historyImages">历史图像数组</param>  
  488.         /// <returns>返回训练是否成功</returns>  
  489.         public bool TrainBackgroundModel(List<Image<Ycc,byte>> historyImages)  
  490.         {  
  491.             AddHistoryImage(historyImages);  
  492.             return TrainBackgroundModel();  
  493.         }  
  494.   
  495.         /// <summary>  
  496.         /// 训练背景模型  
  497.         /// </summary>  
  498.         /// <param name="historyImages">历史图像数组</param>  
  499.         /// <returns>返回训练是否成功</returns>  
  500.         public bool TrainBackgroundModel(Image<Bgr, byte>[] historyImages)  
  501.         {  
  502.             AddHistoryImage(historyImages);  
  503.             return TrainBackgroundModel();  
  504.         }  
  505.   
  506.         /// <summary>  
  507.         /// 训练背景模型  
  508.         /// </summary>  
  509.         /// <param name="historyImages">历史图像数组</param>  
  510.         /// <returns>返回训练是否成功</returns>  
  511.         public bool TrainBackgroundModel(List<Image<Bgr, byte>> historyImages)  
  512.         {  
  513.             AddHistoryImage(historyImages);  
  514.             return TrainBackgroundModel();  
  515.         }  
  516.   
  517.         /// <summary>  
  518.         /// 得到Ycc列表中的最小值(仅比较Y分量)  
  519.         /// </summary>  
  520.         /// <param name="yccList"></param>  
  521.         /// <returns></returns>  
  522.         private Ycc MinYcc(List<Ycc> yccList)  
  523.         {  
  524.             Ycc min = yccList[0];  
  525.             foreach (Ycc ycc in yccList)  
  526.             {  
  527.                 if (ycc.Y < min.Y)  
  528.                     min = ycc;  
  529.             }  
  530.             return min;  
  531.         }  
  532.   
  533.         /// <summary>  
  534.         /// 得到聚集中心列表中的最大值(比较wi)  
  535.         /// </summary>  
  536.         /// <param name="clusterCenters"></param>  
  537.         /// <returns></returns>  
  538.         private ClusterCenter<Ycc> MaxClusterCenter(List<ClusterCenter<Ycc>> clusterCenters)  
  539.         {  
  540.             ClusterCenter<Ycc> max = clusterCenters[0];  
  541.             foreach (ClusterCenter<Ycc> center in clusterCenters)  
  542.             {  
  543.                 if (center.wi > max.wi)  
  544.                     max = center;  
  545.             }  
  546.             return max;  
  547.         }  
  548.   
  549.         /// <summary>  
  550.         /// 得到最可靠背景模型MRBM:在聚集中心选择wi最大的值(没有使用指针运算进行优化,用于演示流程)  
  551.         /// </summary>  
  552.         private void GetMrbm2()  
  553.         {  
  554.             //遍历图像的每一行  
  555.             for (int row = 0; row < height; row++)  
  556.             {  
  557.                 //遍历图像的每一列  
  558.                 for (int col = 0; col < width; col++)  
  559.                     mrbm[row, col] = MaxClusterCenter(clusterCenters[row, col]).ci;  
  560.             }  
  561.         }  
  562.   
  563.         /// <summary>  
  564.         /// 得到最可靠背景模型MRBM:在聚集中心选择wi最大的值  
  565.         /// </summary>  
  566.         unsafe private void GetMrbm()  
  567.         {  
  568.             int widthStepMrbm = mrbm.MIplImage.widthStep;  
  569.             byte* ptrMrbm = (byte*)mrbm.MIplImage.imageData.ToPointer();  
  570.             byte* ptrPixel;  
  571.             Ycc ci;  
  572.             //遍历图像的每一行  
  573.             for (int row = 0; row < height; row++)  
  574.             {  
  575.                 //遍历图像的每一列  
  576.                 for (int col = 0; col < width; col++)  
  577.                 {  
  578.                     ci = MaxClusterCenter(clusterCenters[row, col]).ci;  
  579.                     ptrPixel = ptrMrbm + row * widthStepMrbm + col * 3;  
  580.                     *ptrPixel = (byte)ci.Y;  
  581.                     *(ptrPixel + 1) = (byte)ci.Cr;  
  582.                     *(ptrPixel + 2) = (byte)ci.Cb;  
  583.                 }  
  584.             }  
  585.         }  
  586.   
  587.         /// <summary>  
  588.         /// 更新背景模型,同时计算相应的前景和背景(没有使用指针运算进行优化,用于演示流程)  
  589.         /// </summary>  
  590.         /// <param name="currentFrame">当前帧图像</param>  
  591.         private void Update2(Image<Ycc, byte> currentFrame)  
  592.         {  
  593.             //1.将当前帧加入到历史图像的末尾  
  594.             AddHistoryImage(currentFrame);  
  595.             frameCount++;  
  596.             //2.将背景掩码图像整个设置为白色,在检测时再将前景像素置零  
  597.             backgroundMask.SetValue(255d);  
  598.             //3.遍历图像的每个像素,确定前景或背景;同时进行背景维持操作。  
  599.             int numberPerGroup = param.n / param.m;  
  600.             int lastIdx = param.n - 1;  
  601.             //遍历图像的每一行  
  602.             for (int row = 0; row < height; row++)  
  603.             {  
  604.                 //遍历图像的每一列  
  605.                 for (int col = 0; col < width; col++)  
  606.                 {  
  607.                     int nearestIndex;   //最近的聚集中心索引  
  608.                     double d = GetMinD(historyImages[lastIdx][row, col].Y, clusterCenters[row, col], out nearestIndex);    //得到最小差值d  
  609.                     if (d > param.t)  
  610.                     {  
  611.                         //该点为前景:以该点附近的矩形窗{n-numberPerGroup,0,numberPerGroup,1}开始进行MeanShift运算,并得到新的收敛中心Cnew(wi=1/m),将Cnew加入到聚集中心clusterCenters  
  612.                         //用历史图像在该点的Y通道值组成一副用于Mean Shift计算的样本图像  
  613.                         for (int sampleIdx = 0; sampleIdx < param.n; sampleIdx++)  
  614.                             sampleImage[0, sampleIdx] = new Gray(historyImages[sampleIdx][row, col].Y);     //这里可以用指针运算来提高速度  
  615.                         Rectangle window = new Rectangle(param.n - numberPerGroup, 0, numberPerGroup, 1);  
  616.                         MCvConnectedComp comp;  
  617.                         CvInvoke.cvMeanShift(sampleImage.Ptr, window, param.criteria, out comp);  
  618.                         int center = comp.rect.Left + comp.rect.Width / 2;      //收敛中心  
  619.                         ClusterCenter<Ycc> cnew = new ClusterCenter<Ycc>(historyImages[center][row, col], 1d / (param.m + frameCount), 1d, frameCount);  //将收敛中心作为新的聚集中心  
  620.                         clusterCenters[row, col].Add(cnew);  
  621.                         //设置背景掩码图像的前景点  
  622.                         backgroundMask[row, col] = new Gray(0d);  
  623.                     }  
  624.                     else  
  625.                     {  
  626.                         //该点为背景:更新最近聚集中心的ci为(li+1)/m  
  627.                         clusterCenters[row, col][nearestIndex].li++;  
  628.                         clusterCenters[row, col][nearestIndex].wi = clusterCenters[row, col][nearestIndex].li / (param.m + frameCount);  
  629.                         clusterCenters[row, col][nearestIndex].updateFrameNo = frameCount;  
  630.                     }  
  631.                 }  
  632.             }  
  633.             //4.生成最可靠背景模型  
  634.             GetMrbm();  
  635.         }  
  636.   
  637.         /// <summary>  
  638.         /// 更新背景模型,同时计算相应的前景和背景  
  639.         /// </summary>  
  640.         /// <param name="currentFrame">当前帧图像</param>  
  641.         private void Update2(Image<Bgr, byte> currentFrame)  
  642.         {  
  643.             Image<Ycc, byte> image = currentFrame.Convert<Ycc, byte>();  
  644.             Update(image);  
  645.             image.Dispose();  
  646.         }  
  647.   
  648.         /// <summary>  
  649.         /// 更新背景模型,同时计算相应的前景和背景  
  650.         /// </summary>  
  651.         /// <param name="currentFrame">当前帧图像</param>  
  652.         unsafe public void Update(Image<Ycc, byte> currentFrame)  
  653.         {  
  654.             //1.将当前帧加入到历史图像的末尾  
  655.             AddHistoryImage(currentFrame);  
  656.             frameCount++;  
  657.             //2.将背景掩码图像整个设置为白色,在检测时再将前景像素置零  
  658.             backgroundMask.SetValue(255d);  
  659.             //3.遍历图像的每个像素,确定前景或背景;同时进行背景维持操作。  
  660.             int numberPerGroup = param.n / param.m;  
  661.             int lastIdx = param.n - 1;  
  662.             int offsetHistoryImage;                                                     //历史图像中某个像素相对图像数据起点的偏移量  
  663.             int widthStepHistoryImage = historyImages[0].MIplImage.widthStep;           //历史图像的每行字节数  
  664.             byte*[] ptrHistoryImages = new byte*[param.n];                              //历史图像的数据部分起点数组  
  665.             byte* ptrSampleImage = (byte*)sampleImage.MIplImage.imageData.ToPointer();  //样本图像的数据部分起点  
  666.             int widthStepBackgroundMask = backgroundMask.MIplImage.widthStep;           //背景掩码图像的每行字节数  
  667.             byte* ptrBackgroundMask = (byte*)backgroundMask.MIplImage.imageData.ToPointer();  //背景掩码图像的数据部分起点  
  668.             byte f = 0;                                                                 //前景对应的颜色值  
  669.             for (int i = 0; i < param.n; i++)  
  670.                 ptrHistoryImages[i] = (byte*)historyImages[i].MIplImage.imageData.ToPointer();  
  671.             //遍历图像的每一行  
  672.             for (int row = 0; row < height; row++)  
  673.             {  
  674.                 //遍历图像的每一列  
  675.                 for (int col = 0; col < width; col++)  
  676.                 {  
  677.                     offsetHistoryImage = row * widthStepHistoryImage + col * 3;  
  678.                     int nearestIndex;   //最近的聚集中心索引  
  679.                     double d = GetMinD((double)(*(ptrHistoryImages[lastIdx] + offsetHistoryImage)), clusterCenters[row, col], out nearestIndex);    //得到最小差值d  
  680.                     if (d > param.t)  
  681.                     {  
  682.                         //该点为前景:以该点附近的矩形窗{n-numberPerGroup,0,numberPerGroup,1}开始进行MeanShift运算,并得到新的收敛中心Cnew(wi=1/m),将Cnew加入到聚集中心clusterCenters  
  683.                         //用历史图像在该点的Y通道值组成一副用于Mean Shift计算的样本图像  
  684.                         for (int sampleIdx = 0; sampleIdx < param.n; sampleIdx++)  
  685.                             *(ptrSampleImage + sampleIdx) = *(ptrHistoryImages[sampleIdx] + offsetHistoryImage);  
  686.                         Rectangle window = new Rectangle(param.n - numberPerGroup, 0, numberPerGroup, 1);  
  687.                         MCvConnectedComp comp;  
  688.                         CvInvoke.cvMeanShift(sampleImage.Ptr, window, param.criteria, out comp);  
  689.                         int center = comp.rect.Left + comp.rect.Width / 2;      //收敛中心  
  690.                         ClusterCenter<Ycc> cnew = new ClusterCenter<Ycc>(historyImages[center][row, col], 1d / (param.m + frameCount), 1d, frameCount);  //将收敛中心作为新的聚集中心  
  691.                         clusterCenters[row, col].Add(cnew);  
  692.                         //设置背景掩码图像的前景点  
  693.                         *(ptrBackgroundMask + row * widthStepBackgroundMask + col) = f;  
  694.                     }  
  695.                     else  
  696.                     {  
  697.                         //该点为背景:更新最近聚集中心的ci为(li+1)/m  
  698.                         clusterCenters[row, col][nearestIndex].li++;  
  699.                         clusterCenters[row, col][nearestIndex].wi = clusterCenters[row, col][nearestIndex].li / (param.m + frameCount);  
  700.                         clusterCenters[row, col][nearestIndex].updateFrameNo = frameCount;  
  701.                     }  
  702.                 }  
  703.             }  
  704.             //4.生成最可靠背景模型  
  705.             GetMrbm();  
  706.         }  
  707.   
  708.         public void Update(Image<Bgr, byte> currentFrame)  
  709.         {  
  710.             Image<Ycc, byte> image = currentFrame.Convert<Ycc, byte>();  
  711.             Update(image);  
  712.             image.Dispose();  
  713.         }  
  714.   
  715.         /// <summary>  
  716.         /// 用wi>=theta作为条件选择可能的背景模型Cb;对每个观测值x0,计算x0与Cb的最小差值d  
  717.         /// </summary>  
  718.         /// <param name="x0">观测值x0</param>  
  719.         /// <param name="centerList">某像素对应的聚集中心列表</param>  
  720.         /// <param name="nearestIndex">输出参数:最近的聚集中心索引</param>  
  721.         /// <returns>返回最小差值d</returns>  
  722.         private double GetMinD(double x0, List<ClusterCenter<Ycc>> centerList, out int nearestIndex)  
  723.         {  
  724.             double d = double.MaxValue;  
  725.             nearestIndex = 0;  
  726.             for (int idx = 0; idx < centerList.Count; idx++)  
  727.             {  
  728.                 ClusterCenter<Ycc> center = centerList[idx];  
  729.                 if (center.wi >= param.theta)  
  730.                 {  
  731.                     double d0 = Math.Abs(center.ci.Y - x0);  
  732.                     if (d0 < d)  
  733.                     {  
  734.                         d = d0;  
  735.                         nearestIndex = idx;  
  736.                     }  
  737.                 }  
  738.             }  
  739.             return d;  
  740.         }  
  741.   
  742.         /// <summary>  
  743.         /// 清除不活跃的聚集中心  
  744.         /// </summary>  
  745.         /// <param name="staleThresh">不活跃阀值,不活跃帧数大于该值的聚集中心将被清除</param>  
  746.         public void ClearStale(int staleThresh)  
  747.         {  
  748.             //遍历每个像素的聚集中心  
  749.             for (int row = 0; row < height; row++)  
  750.             {  
  751.                 for (int col = 0; col < width; col++)  
  752.                 {  
  753.                     for (int idx = clusterCenters[row, col].Count - 1; idx >= 0; idx--)  
  754.                     {  
  755.                         if (frameCount - clusterCenters[row, col][idx].updateFrameNo > staleThresh)  
  756.                             clusterCenters[row, col].RemoveAt(idx);  
  757.                     }  
  758.                 }  
  759.             }  
  760.         }  
  761.   
  762.     }  
  763.   
  764.     /// <summary>  
  765.     /// 聚集中心  
  766.     /// </summary>  
  767.     /// <typeparam name="TColor">聚集中心使用的色彩空间</typeparam>  
  768.     public class ClusterCenter<TColor>  
  769.         where TColor : struct, IColor  
  770.     {  
  771.         public TColor ci;              //聚集中心的像素值  
  772.         public double wi;              //聚集中心的权重  
  773.         public double li;              //聚集中心包含的收敛点数目  
  774.         public double updateFrameNo;   //更新该聚集中心时的帧数:用于消除消极的聚集中心  
  775.   
  776.         public ClusterCenter(TColor ci, double wi, double li, double updateFrameNo)  
  777.         {  
  778.             this.ci = ci;  
  779.             this.li = li;  
  780.             this.wi = wi;  
  781.             this.updateFrameNo = updateFrameNo;  
  782.         }  
  783.     }  
  784.   
  785.     /// <summary>  
  786.     /// 非参数背景模型的参数  
  787.     /// </summary>  
  788.     public struct NBGParameter  
  789.     {  
  790.         public int n;                       //样本数目:需要被保留的历史图像数目  
  791.         public int m;                       //典型点数目:历史图像需要被分为多少组  
  792.         public double theta;                //权重系数:权重大于该值的聚集中心为候选背景  
  793.         public double t;                    //最小差值:观测值与候选背景的最小差值大于该值时,为前景;否则为背景  
  794.         public MCvTermCriteria criteria;    //Mean Shift计算的终止条件:包括最大迭代次数和终止计算的精度  
  795.   
  796.         public NBGParameter(int n, int m, double theta, double t, MCvTermCriteria criteria)  
  797.         {  
  798.             this.n = n;  
  799.             this.m = m;  
  800.             this.theta = theta;  
  801.             this.t = t;  
  802.             this.criteria.type = criteria.type;  
  803.             this.criteria.max_iter = criteria.max_iter;  
  804.             this.criteria.epsilon = criteria.epsilon;  
  805.         }  
  806.   
  807.         public static NBGParameter GetDefaultNBGParameter()  
  808.         {  
  809.             return new NBGParameter(100, 10, 0.3d, 10d, new MCvTermCriteria(100, 1d));  
  810.         }  
  811.     }  
  812. }  

3 NBGModel类介绍
    3.1 属性
Width——获取图像的宽度
Height——获取图像的高度
Param——获取参数设置
Mrbm——获取最可靠背景模型图像
BackgroundMask——获取背景掩码图像
ForegroundMask——获取前景掩码图像
FrameCount——获取已被检测的帧数

    3.2 构造函数
public NBGModel(int width, int height)——用默认的参数初始化NBGModel,等价于NBGModel(width, height, NBGParameter.GetDefaultNBGParameter())
public NBGModel(int width, int height, NBGParameter param)——用指定的参数初始化NBGModel

    3.3 方法
AddHistoryImage——添加一幅或者一组历史图像
TrainBackgroundModel——训练背景模型;如果传入了历史图像,则先添加历史图像,然后再训练背景模型
Update——更新背景模型,同时检测前景
ClearStale——清除消极的聚集中心
Dispose——释放资源

4 体会
    NBGModel的确非常有效,非常简洁,特别适用于伴随复杂运动对象的背景建模。我特意选取了PETS2009中的素材对其做了一些测试,结果也证明了NBGModel的优越性。不过需要指出的是,它需要占用大量的内存(主要因为需要保存n幅历史图像);它的计算量比较大。
在使用的过程中,它始终需要在内存中缓存n幅历史图像,1幅最可靠背景模型图像,1幅背景掩码图像,近似m幅图像(聚集中心);而在训练阶段,更需要临时存储m幅收敛图像。
例如:样本数目为100,典型点数目为10,图像尺寸为768x576时,所用的内存接近300M,训练背景需要大约需要33秒,而对每幅图像进行前景检测大约需要600ms。虽然可以使用并行编程来提高性能,但是并不能从根本上解决问题。
(注:测试电脑的CPU为AMD闪龙3200+,内存1.5G。)
    看来,有必要研究一种新的方法,目标是检测效果更好,内存占用低,处理更快速。目前的想法是使用《Wallflower: Principles and Practice of Background Manitenance》中的3层架构(时间轴上的像素级处理,像素间的区域处理,帧间处理),但是对每层架构都选用目前流行的处理方式,并对处理方式进行优化。时间轴上的像素级处理打算使用CodeBook方法,但是增加本文的一些思想。像素间的区域处理打算参考《基于区域相关的核函数背景建模算法》中的方法。帧间处理预计会采用全局灰度统计值作为依据。

最后,按照惯例:感谢您耐心看完本文,希望对您有所帮助。
本文所述方法及代码仅用于学习研究,不得用于商业目的。




背景模型-颜色特征与纹理特征融合 

转自:http://www.cnblogs.com/dwdxdy/archive/2012/06/01/2530378.html

参考文献 Multi-Layer Background Subtraction Based on Color and Texture CVPR-VS 2007

与前一篇文章的大体思路一致,提取纹理特征和颜色特征,建立背景模型,并实时更新背景模型.

纹理特征:LBP.

颜色特征:借鉴码本模型,颜色空间的分布模型,参用当前像素点与背景像素点的夹角,以及最小和最大值作为颜色特征.

纹理特征相似度计算:

颜色特征相似度计算:

最终的相似度计算,是纹理特征和颜色特征相似度的加权和.

背景模描述:

背景更新,与前一篇文章类似,只不过其权值更新的学习因子,是根据该模型最大权值的大小来调整的.

对于当前权值较小, 但是曾经具有大权值的模型如果出现匹配情况时权值的增加非常快.

对于当前权值较小,但是曾经具有大权值的模型如果出现不匹配情况时权值的减少非常慢.

对于曾经具有过大权值的模型, 其实很可能属于背景模型,

当再次出现匹配这类模型的像素时, 快速恢复其权值是非常合理的,

不匹配这类模型时,缓慢减少其权值是合理的.

其存在匹配的模型时,对应的的第k个模型更新公式如下:

其他模型,只更新其权值,其他的保持不变,

前景检测的步骤:

1).计算与背景模型中K个模型的最小距离,记最小距离的模型为第i个模型.

2).判断第i个模型,是否为背景模型,是否曾经可判断为可信的背景模型.

3).若是,则保持最小距离不变,若不是,则更新最小距离的值.

4).利用the cross bilateral filter平滑最小距离值.

5).根据最小距离值与阈值的大小,确定对应像素点是前景,还是背景.

其具体计算公式如下:

本文创新点:

1).颜色特征的选择.

2).权值的更新方式,利用了权值对应的历史信息.

3).引入分层的概念,利用模型被匹配为可信背景模型的历史信息,来判断当前模型匹配的可信度.

4).在计算得最小距离值,进行平滑处理,而不是得到前景和背景后再做平滑处理.

不足之处:参数的选择和阈值的选择对检测结果的影响,如何选择最合适的一组参数值.

 

参考文献 基于颜色和纹理特征背景模型的多层差分运动目标检测算法 计算机应用 2009

初看这篇文章,感觉与上面的英语文章有许多类似之处,不过细看,仍有些不同之处.

1).该文是将纹理特征和颜色特征分开进行匹配计算,得到两种特征下结果,最后再将两种结果融合.

2).该文中纹理特征匹配和更新时,其与混合高斯模型的思路一致,利用方差来调整匹配对应的阈值.

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值