Mean-Shift算法

原文地址:http://blog.csdn.net/hjimce/article/details/45718593 

作者:hjimce

一、mean shift 算法理论

Mean shift 算法是基于核密度估计的爬山算法,可用于聚类、图像分割、跟踪等,因为最近搞一个项目,涉及到这个算法的图像聚类实现,因此这里做下笔记。

(1)均值漂移的基本形式

给定d维空间的n个数据点集X,那么对于空间中的任意点x的mean shift向量基本形式可以表示为:

 

这个向量就是漂移向量,其中Sk表示的是数据集的点到x的距离小于球半径h的数据点。也就是:

 

而漂移的过程,说的简单一点,就是通过计算得漂移向量,然后把球圆心x的位置更新一下,更新公式为:

 

使得圆心的位置一直处于力的平衡位置。

 

 

总结为一句话就是:求解一个向量,使得圆心一直往数据集密度最大的方向移动。说的再简单一点,就是每次迭代的时候,都是找到圆里面点的平均位置作为新的圆心位置。

(2)加入核函数的漂移向量

这个说的简单一点就是加入一个高斯权重,最后的漂移向量计算公式为:

因此每次更新的圆心坐标为:

 

不过我觉得如果用高斯核函数,把这个算法称为均值漂移有点不合理,既然叫均值漂移,那么均值应该指的是权重相等,也就是(1)中的公式才能称之为真正的均值漂移。

我的简单理解mean shift算法是:物理学上力的合成与物体的运动。每次迭代通过求取力的合成向量,然后让圆心沿着力的合成方向,移动到新的平衡位置。

二、mean shift 聚类流程:

假设在一个多维空间中有很多数据点需要进行聚类,Mean Shift的过程如下:

1、在未被标记的数据点中随机选择一个点作为中心center;

2、找出离center距离在bandwidth之内的所有点,记做集合M,认为这些点属于簇c。同时,把这些求内点属于这个类的概率加1,这个参数将用于最后步骤的分类

3、以center为中心点,计算从center开始到集合M中每个元素的向量,将这些向量相加,得到向量shift。

4、center = center+shift。即center沿着shift的方向移动,移动距离是||shift||。

5、重复步骤2、3、4,直到shift的大小很小(就是迭代到收敛),记住此时的center。注意,这个迭代过程中遇到的点都应该归类到簇c。

6、如果收敛时当前簇c的center与其它已经存在的簇c2中心的距离小于阈值,那么把c2和c合并。否则,把c作为新的聚类,增加1类。

6、重复1、2、3、4、5直到所有的点都被标记访问。

7、分类:根据每个类,对每个点的访问频率,取访问频率最大的那个类,作为当前点集的所属类。

简单的说,mean shift就是沿着密度上升的方向寻找同属一个簇的数据点。

三、mean shift 聚类实现

Mean shift 算法不需要指定聚类个数,贴一下用matlab实现的聚类结果:

 

[c++]  view plain  copy

 

  1. clc  
  2. close all;  
  3. clear  
  4. profile on  
  5. %生成随机数据点集  
  6. nPtsPerClust = 250;  
  7. nClust  = 3;  
  8. totalNumPts = nPtsPerClust*nClust;  
  9. m(:,1) = [1 1]';  
  10. m(:,2) = [-1 -1]';  
  11. m(:,3) = [1 -1]';  
  12. var = .6;  
  13. bandwidth = .75;  
  14. clustMed = [];  
  15. x = var*randn(2,nPtsPerClust*nClust);  
  16. for i = 1:nClust  
  17.     x(:,1+(i-1)*nPtsPerClust:(i)*nPtsPerClust)       = x(:,1+(i-1)*nPtsPerClust:(i)*nPtsPerClust) + repmat(m(:,i),1,nPtsPerClust);     
  18. end  
  19. data=x';  
  20. % plot(data(:,1),data(:,2),'.')  
  21.   
  22.   
  23. %mean shift 算法  
  24. [m,n]=size(data);  
  25. index=1:m;  
  26. radius=0.75;  
  27. stopthresh=1e-3*radius;  
  28. visitflag=zeros(m,1);%标记是否被访问  
  29. count=[];  
  30. clustern=0;  
  31. clustercenter=[];  
  32.   
  33. hold on;  
  34. while length(index)>0  
  35.     cn=ceil((length(index)-1e-6)*rand);%随机选择一个未被标记的点,作为圆心,进行均值漂移迭代  
  36.     center=data(index(cn),:);  
  37.     this_class=zeros(m,1);%统计漂移过程中,每个点的访问频率  
  38.       
  39.       
  40.     %步骤2、3、4、5  
  41.     while 1  
  42.         %计算球半径内的点集  
  43.         dis=sum((repmat(center,m,1)-data).^2,2);  
  44.         radius2=radius*radius;  
  45.         innerS=find(dis<radius*radius);  
  46.         visitflag(innerS)=1;%在均值漂移过程中,记录已经被访问过得点  
  47.         this_class(innerS)=this_class(innerS)+1;  
  48.         %根据漂移公式,计算新的圆心位置  
  49.         newcenter=zeros(1,2);  
  50.        % newcenter= mean(data(innerS,:),1);   
  51.         sumweight=0;  
  52.         for i=1:length(innerS)  
  53.             w=exp(dis(innerS(i))/(radius*radius));  
  54.             sumweight=w+sumweight;  
  55.             newcenter=newcenter+w*data(innerS(i),:);  
  56.         end  
  57.         newcenter=newcenter./sumweight;  
  58.   
  59.         if norm(newcenter-center) <stopthresh%计算漂移距离,如果漂移距离小于阈值,那么停止漂移  
  60.             break;  
  61.         end  
  62.         center=newcenter;  
  63.         plot(center(1),center(2),'*y');  
  64.     end  
  65.     %步骤6 判断是否需要合并,如果不需要则增加聚类个数1个  
  66.     mergewith=0;  
  67.     for i=1:clustern  
  68.         betw=norm(center-clustercenter(i,:));  
  69.         if betw<radius/2  
  70.             mergewith=i;   
  71.             break;  
  72.         end  
  73.     end  
  74.     if mergewith==0           %不需要合并  
  75.         clustern=clustern+1;  
  76.         clustercenter(clustern,:)=center;  
  77.         count(:,clustern)=this_class;  
  78.     else                      %合并  
  79.         clustercenter(mergewith,:)=0.5*(clustercenter(mergewith,:)+center);  
  80.         count(:,mergewith)=count(:,mergewith)+this_class;    
  81.     end  
  82.     %重新统计未被访问过的点  
  83.     index=find(visitflag==0);  
  84. end%结束所有数据点访问  
  85.   
  86. %绘制分类结果  
  87. for i=1:m  
  88.     [value index]=max(count(i,:));  
  89.     Idx(i)=index;  
  90. end  
  91. figure(2);  
  92. hold on;  
  93. for i=1:m  
  94.     if Idx(i)==1;  
  95.         plot(data(i,1),data(i,2),'.y');  
  96.     elseif Idx(i)==2;  
  97.          plot(data(i,1),data(i,2),'.b');  
  98.     elseif Idx(i)==3;  
  99.          plot(data(i,1),data(i,2),'.r');  
  100.     elseif Idx(i)==4;  
  101.          plot(data(i,1),data(i,2),'.k');  
  102.     elseif Idx(i)==5;  
  103.          plot(data(i,1),data(i,2),'.g');  
  104.     end  
  105. end  
  106. cVec = 'bgrcmykbgrcmykbgrcmykbgrcmyk';  
  107. for k = 1:clustern  
  108.     plot(clustercenter(k,1),clustercenter(k,2),'o','MarkerEdgeColor','k','MarkerFaceColor',cVec(k), 'MarkerSize',10)  
  109. end  

 

 

在图像分割、图像跟踪,需要加入核函数。

 

聚类结果                                                                                           圆心漂移轨迹

*********作者:hjimce     联系qq:1393852684   更多资源请关注我的博客:http://blog.csdn.net/hjimce                原创文章,转载请保留本行信息。*****************

 

第二篇转自:http://blog.csdn.net/jinshengtao/article/details/30258833,版权归原作者所有。

 

一、简介

     首先扯扯无参密度估计理论,无参密度估计也叫做非参数估计,属于数理统计的一个分支,和参数密度估计共同构成了概率密度估计方法。参数密度估计方法要求特征空间服从一个已知的概率密度函数,在实际的应用中这个条件很难达到。而无参数密度估计方法对先验知识要求最少,完全依靠训练数据进行估计,并且可以用于任意形状的密度估计。所以依靠无参密度估计方法,即不事先规定概率密度函数的结构形式,在某一连续点处的密度函数值可由该点邻域中的若干样本点估计得出。常用的无参密度估计方法有:直方图法、最近邻域法和核密度估计法。

     MeanShift算法正是属于核密度估计法,它不需要任何先验知识而完全依靠特征空间中样本点的计算其密度函数值。对于一组采样数据,直方图法通常把数据的值域分成若干相等的区间,数据按区间分成若干组,每组数据的个数与总参数个数的比率就是每个单元的概率值;核密度估计法的原理相似于直方图法,只是多了一个用于平滑数据的核函数。采用核函数估计法,在采样充分的情况下,能够渐进地收敛于任意的密度函数,即可以对服从任何分布的数据进行密度估计。

     然后谈谈MeanShift的基本思想及物理含义:

    此外,从公式1中可以看到,只要是落入Sh的采样点,无论其离中心x的远近,对最终的Mh(x)计算的贡献是一样的。然而在现实跟踪过程中,当跟踪目标出现遮挡等影响时,由于外层的像素值容易受遮挡或背景的影响,所以目标模型中心附近的像素比靠外的像素更可靠。因此,对于所有采样点,每个样本点的重要性应该是不同的,离中心点越远,其权值应该越小。故引入核函数和权重系数来提高跟踪算法的鲁棒性并增加搜索跟踪能力。

      接下来,谈谈核函数:

    核函数也叫窗口函数,在核估计中起到平滑的作用。常用的核函数有:Uniform,Epannechnikov,Gaussian等。本文算法只用到了Epannechnikov,它数序定义如下:

二、基于MeanShift的目标跟踪算法

     基于均值漂移的目标跟踪算法通过分别计算目标区域和候选区域内像素的特征值概率得到关于目标模型和候选模型的描述,然后利用相似函数度量初始帧目标模型和当前帧的候选模版的相似性,选择使相似函数最大的候选模型并得到关于目标模型的Meanshift向量,这个向量正是目标由初始位置向正确位置移动的向量。由于均值漂移算法的快速收敛性,通过不断迭代计算Meanshift向量,算法最终将收敛到目标的真实位置,达到跟踪的目的。

     下面通过图示直观的说明MeanShift跟踪算法的基本原理。如下图所示:目标跟踪开始于数据点xi0(空心圆点xi0,xi1,…,xiN表示的是中心点,上标表示的是的迭代次数,周围的黑色圆点表示不断移动中的窗口样本点,虚线圆圈代表的是密度估计窗口的大小)。箭头表示样本点相对于核函数中心点的漂移向量,平均的漂移向量会指向样本点最密集的方向,也就是梯度方向。因为 Meanshift 算法是收敛的,因此在当前帧中通过反复迭代搜索特征空间中样本点最密集的区域,搜索点沿着样本点密度增加的方向“漂移”到局部密度极大点点xiN,也就是被认为的目标位置,从而达到跟踪的目的,MeanShift 跟踪过程结束。

 

 

运动目标的实现过程【具体算法】:

 

三、代码实现

说明:

1.       RGB颜色空间刨分,采用16*16*16的直方图

2.       目标模型和候选模型的概率密度计算公式参照上文

3.       opencv版本运行:按P停止,截取目标,再按P,进行单目标跟踪

4.       Matlab版本,将视频改为图片序列,第一帧停止,手工标定目标,双击目标区域,进行单目标跟踪。

 

matlab版本:

 

 
  1. function [] = select()

  2. close all;

  3. clear all;

  4. %%%%%%%%%%%%%%%%%%根据一幅目标全可见的图像圈定跟踪目标%%%%%%%%%%%%%%%%%%%%%%%

  5. I=imread('result72.jpg');

  6. figure(1);

  7. imshow(I);

  8.  
  9.  
  10. [temp,rect]=imcrop(I);

  11. [a,b,c]=size(temp); %a:row,b:col

  12.  
  13.  
  14. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%计算目标图像的权值矩阵%%%%%%%%%%%%%%%%%%%%%%%

  15. y(1)=a/2;

  16. y(2)=b/2;

  17. tic_x=rect(1)+rect(3)/2;

  18. tic_y=rect(2)+rect(4)/2;

  19. m_wei=zeros(a,b);%权值矩阵

  20. h=y(1)^2+y(2)^2 ;%带宽

  21.  
  22.  
  23. for i=1:a

  24. for j=1:b

  25. dist=(i-y(1))^2+(j-y(2))^2;

  26. m_wei(i,j)=1-dist/h; %epanechnikov profile

  27. end

  28. end

  29. C=1/sum(sum(m_wei));%归一化系数

  30.  
  31.  
  32. %计算目标权值直方图qu

  33. %hist1=C*wei_hist(temp,m_wei,a,b);%target model

  34. hist1=zeros(1,4096);

  35. for i=1:a

  36. for j=1:b

  37. %rgb颜色空间量化为16*16*16 bins

  38. q_r=fix(double(temp(i,j,1))/16); %fix为趋近0取整函数

  39. q_g=fix(double(temp(i,j,2))/16);

  40. q_b=fix(double(temp(i,j,3))/16);

  41. q_temp=q_r*256+q_g*16+q_b; %设置每个像素点红色、绿色、蓝色分量所占比重

  42. hist1(q_temp+1)= hist1(q_temp+1)+m_wei(i,j); %计算直方图统计中每个像素点占的权重

  43. end

  44. end

  45. hist1=hist1*C;

  46. rect(3)=ceil(rect(3));

  47. rect(4)=ceil(rect(4));

  48.  
  49.  
  50.  
  51.  
  52. %%%%%%%%%%%%%%%%%%%%%%%%%读取序列图像

  53. myfile=dir('D:\matlab7\work\mean shift\image\*.jpg');

  54. lengthfile=length(myfile);

  55.  
  56.  
  57. for l=1:lengthfile

  58. Im=imread(myfile(l).name);

  59. num=0;

  60. Y=[2,2];

  61.  
  62.  
  63. %%%%%%%mean shift迭代

  64. while((Y(1)^2+Y(2)^2>0.5)&num<20) %迭代条件

  65. num=num+1;

  66. temp1=imcrop(Im,rect);

  67. %计算侯选区域直方图

  68. %hist2=C*wei_hist(temp1,m_wei,a,b);%target candidates pu

  69. hist2=zeros(1,4096);

  70. for i=1:a

  71. for j=1:b

  72. q_r=fix(double(temp1(i,j,1))/16);

  73. q_g=fix(double(temp1(i,j,2))/16);

  74. q_b=fix(double(temp1(i,j,3))/16);

  75. q_temp1(i,j)=q_r*256+q_g*16+q_b;

  76. hist2(q_temp1(i,j)+1)= hist2(q_temp1(i,j)+1)+m_wei(i,j);

  77. end

  78. end

  79. hist2=hist2*C;

  80. figure(2);

  81. subplot(1,2,1);

  82. plot(hist2);

  83. hold on;

  84.  
  85. w=zeros(1,4096);

  86. for i=1:4096

  87. if(hist2(i)~=0) %不等于

  88. w(i)=sqrt(hist1(i)/hist2(i));

  89. else

  90. w(i)=0;

  91. end

  92. end

  93.  
  94.  
  95.  
  96. %变量初始化

  97. sum_w=0;

  98. xw=[0,0];

  99. for i=1:a;

  100. for j=1:b

  101. sum_w=sum_w+w(uint32(q_temp1(i,j))+1);

  102. xw=xw+w(uint32(q_temp1(i,j))+1)*[i-y(1)-0.5,j-y(2)-0.5];

  103. end

  104. end

  105. Y=xw/sum_w;

  106. %中心点位置更新

  107. rect(1)=rect(1)+Y(2);

  108. rect(2)=rect(2)+Y(1);

  109. end

  110.  
  111.  
  112. %%%跟踪轨迹矩阵%%%

  113. tic_x=[tic_x;rect(1)+rect(3)/2];

  114. tic_y=[tic_y;rect(2)+rect(4)/2];

  115.  
  116. v1=rect(1);

  117. v2=rect(2);

  118. v3=rect(3);

  119. v4=rect(4);

  120. %%%显示跟踪结果%%%

  121. subplot(1,2,2);

  122. imshow(uint8(Im));

  123. title('目标跟踪结果及其运动轨迹');

  124. hold on;

  125. plot([v1,v1+v3],[v2,v2],[v1,v1],[v2,v2+v4],[v1,v1+v3],[v2+v4,v2+v4],[v1+v3,v1+v3],[v2,v2+v4],'LineWidth',2,'Color','r');

  126. plot(tic_x,tic_y,'LineWidth',2,'Color','b');

  127. end

 

 

 运行结果:

 

 

 

opencv版本:

 

 
  1. #include "stdafx.h"

  2. #include "cv.h"

  3. #include "highgui.h"

  4. #define u_char unsigned char

  5. #define DIST 0.5

  6. #define NUM 20

  7.  
  8. //全局变量

  9. bool pause = false;

  10. bool is_tracking = false;

  11. CvRect drawing_box;

  12. IplImage *current;

  13. double *hist1, *hist2;

  14. double *m_wei; //权值矩阵

  15. double C = 0.0; //归一化系数

  16.  
  17. void init_target(double *hist1, double *m_wei, IplImage *current)

  18. {

  19. IplImage *pic_hist = 0;

  20. int t_h, t_w, t_x, t_y;

  21. double h, dist;

  22. int i, j;

  23. int q_r, q_g, q_b, q_temp;

  24.  
  25. t_h = drawing_box.height;

  26. t_w = drawing_box.width;

  27. t_x = drawing_box.x;

  28. t_y = drawing_box.y;

  29.  
  30. h = pow(((double)t_w)/2,2) + pow(((double)t_h)/2,2); //带宽

  31. pic_hist = cvCreateImage(cvSize(300,200),IPL_DEPTH_8U,3); //生成直方图图像

  32.  
  33. //初始化权值矩阵和目标直方图

  34. for (i = 0;i < t_w*t_h;i++)

  35. {

  36. m_wei[i] = 0.0;

  37. }

  38.  
  39. for (i=0;i<4096;i++)

  40. {

  41. hist1[i] = 0.0;

  42. }

  43.  
  44. for (i = 0;i < t_h; i++)

  45. {

  46. for (j = 0;j < t_w; j++)

  47. {

  48. dist = pow(i - (double)t_h/2,2) + pow(j - (double)t_w/2,2);

  49. m_wei[i * t_w + j] = 1 - dist / h;

  50. //printf("%f\n",m_wei[i * t_w + j]);

  51. C += m_wei[i * t_w + j] ;

  52. }

  53. }

  54.  
  55. //计算目标权值直方

  56. for (i = t_y;i < t_y + t_h; i++)

  57. {

  58. for (j = t_x;j < t_x + t_w; j++)

  59. {

  60. //rgb颜色空间量化为16*16*16 bins

  61. q_r = ((u_char)current->imageData[i * current->widthStep + j * 3 + 2]) / 16;

  62. q_g = ((u_char)current->imageData[i * current->widthStep + j * 3 + 1]) / 16;

  63. q_b = ((u_char)current->imageData[i * current->widthStep + j * 3 + 0]) / 16;

  64. q_temp = q_r * 256 + q_g * 16 + q_b;

  65. hist1[q_temp] = hist1[q_temp] + m_wei[(i - t_y) * t_w + (j - t_x)] ;

  66. }

  67. }

  68.  
  69. //归一化直方图

  70. for (i=0;i<4096;i++)

  71. {

  72. hist1[i] = hist1[i] / C;

  73. //printf("%f\n",hist1[i]);

  74. }

  75.  
  76. //生成目标直方图

  77. double temp_max=0.0;

  78.  
  79. for (i = 0;i < 4096;i++) //求直方图最大值,为了归一化

  80. {

  81. //printf("%f\n",val_hist[i]);

  82. if (temp_max < hist1[i])

  83. {

  84. temp_max = hist1[i];

  85. }

  86. }

  87. //画直方图

  88. CvPoint p1,p2;

  89. double bin_width=(double)pic_hist->width/4096;

  90. double bin_unith=(double)pic_hist->height/temp_max;

  91.  
  92. for (i = 0;i < 4096; i++)

  93. {

  94. p1.x = i * bin_width;

  95. p1.y = pic_hist->height;

  96. p2.x = (i + 1)*bin_width;

  97. p2.y = pic_hist->height - hist1[i] * bin_unith;

  98. //printf("%d,%d,%d,%d\n",p1.x,p1.y,p2.x,p2.y);

  99. cvRectangle(pic_hist,p1,p2,cvScalar(0,255,0),-1,8,0);

  100. }

  101. cvSaveImage("hist1.jpg",pic_hist);

  102. cvReleaseImage(&pic_hist);

  103. }

  104.  
  105. void MeanShift_Tracking(IplImage *current)

  106. {

  107. int num = 0, i = 0, j = 0;

  108. int t_w = 0, t_h = 0, t_x = 0, t_y = 0;

  109. double *w = 0, *hist2 = 0;

  110. double sum_w = 0, x1 = 0, x2 = 0,y1 = 2.0, y2 = 2.0;

  111. int q_r, q_g, q_b;

  112. int *q_temp;

  113. IplImage *pic_hist = 0;

  114.  
  115. t_w = drawing_box.width;

  116. t_h = drawing_box.height;

  117.  
  118. pic_hist = cvCreateImage(cvSize(300,200),IPL_DEPTH_8U,3); //生成直方图图像

  119. hist2 = (double *)malloc(sizeof(double)*4096);

  120. w = (double *)malloc(sizeof(double)*4096);

  121. q_temp = (int *)malloc(sizeof(int)*t_w*t_h);

  122.  
  123. while ((pow(y2,2) + pow(y1,2) > 0.5)&& (num < NUM))

  124. {

  125. num++;

  126. t_x = drawing_box.x;

  127. t_y = drawing_box.y;

  128. memset(q_temp,0,sizeof(int)*t_w*t_h);

  129. for (i = 0;i<4096;i++)

  130. {

  131. w[i] = 0.0;

  132. hist2[i] = 0.0;

  133. }

  134.  
  135. for (i = t_y;i < t_h + t_y;i++)

  136. {

  137. for (j = t_x;j < t_w + t_x;j++)

  138. {

  139. //rgb颜色空间量化为16*16*16 bins

  140. q_r = ((u_char)current->imageData[i * current->widthStep + j * 3 + 2]) / 16;

  141. q_g = ((u_char)current->imageData[i * current->widthStep + j * 3 + 1]) / 16;

  142. q_b = ((u_char)current->imageData[i * current->widthStep + j * 3 + 0]) / 16;

  143. q_temp[(i - t_y) *t_w + j - t_x] = q_r * 256 + q_g * 16 + q_b;

  144. hist2[q_temp[(i - t_y) *t_w + j - t_x]] = hist2[q_temp[(i - t_y) *t_w + j - t_x]] + m_wei[(i - t_y) * t_w + j - t_x] ;

  145. }

  146. }

  147.  
  148. //归一化直方图

  149. for (i=0;i<4096;i++)

  150. {

  151. hist2[i] = hist2[i] / C;

  152. //printf("%f\n",hist2[i]);

  153. }

  154. //生成目标直方图

  155. double temp_max=0.0;

  156.  
  157. for (i=0;i<4096;i++) //求直方图最大值,为了归一化

  158. {

  159. if (temp_max < hist2[i])

  160. {

  161. temp_max = hist2[i];

  162. }

  163. }

  164. //画直方图

  165. CvPoint p1,p2;

  166. double bin_width=(double)pic_hist->width/(4368);

  167. double bin_unith=(double)pic_hist->height/temp_max;

  168.  
  169. for (i = 0;i < 4096; i++)

  170. {

  171. p1.x = i * bin_width;

  172. p1.y = pic_hist->height;

  173. p2.x = (i + 1)*bin_width;

  174. p2.y = pic_hist->height - hist2[i] * bin_unith;

  175. cvRectangle(pic_hist,p1,p2,cvScalar(0,255,0),-1,8,0);

  176. }

  177. cvSaveImage("hist2.jpg",pic_hist);

  178.  
  179. for (i = 0;i < 4096;i++)

  180. {

  181. if (hist2[i] != 0)

  182. {

  183. w[i] = sqrt(hist1[i]/hist2[i]);

  184. }else

  185. {

  186. w[i] = 0;

  187. }

  188. }

  189.  
  190. sum_w = 0.0;

  191. x1 = 0.0;

  192. x2 = 0.0;

  193.  
  194. for (i = 0;i < t_h; i++)

  195. {

  196. for (j = 0;j < t_w; j++)

  197. {

  198. //printf("%d\n",q_temp[i * t_w + j]);

  199. sum_w = sum_w + w[q_temp[i * t_w + j]];

  200. x1 = x1 + w[q_temp[i * t_w + j]] * (i - t_h/2);

  201. x2 = x2 + w[q_temp[i * t_w + j]] * (j - t_w/2);

  202. }

  203. }

  204. y1 = x1 / sum_w;

  205. y2 = x2 / sum_w;

  206.  
  207. //中心点位置更新

  208. drawing_box.x += y2;

  209. drawing_box.y += y1;

  210.  
  211. //printf("%d,%d\n",drawing_box.x,drawing_box.y);

  212. }

  213. free(hist2);

  214. free(w);

  215. free(q_temp);

  216. //显示跟踪结果

  217. cvRectangle(current,cvPoint(drawing_box.x,drawing_box.y),cvPoint(drawing_box.x+drawing_box.width,drawing_box.y+drawing_box.height),CV_RGB(255,0,0),2);

  218. cvShowImage("Meanshift",current);

  219. //cvSaveImage("result.jpg",current);

  220. cvReleaseImage(&pic_hist);

  221. }

  222.  
  223. void onMouse( int event, int x, int y, int flags, void *param )

  224. {

  225. if (pause)

  226. {

  227. switch(event)

  228. {

  229. case CV_EVENT_LBUTTONDOWN:

  230. //the left up point of the rect

  231. drawing_box.x=x;

  232. drawing_box.y=y;

  233. break;

  234. case CV_EVENT_LBUTTONUP:

  235. //finish drawing the rect (use color green for finish)

  236. drawing_box.width=x-drawing_box.x;

  237. drawing_box.height=y-drawing_box.y;

  238. cvRectangle(current,cvPoint(drawing_box.x,drawing_box.y),cvPoint(drawing_box.x+drawing_box.width,drawing_box.y+drawing_box.height),CV_RGB(255,0,0),2);

  239. cvShowImage("Meanshift",current);

  240.  
  241. //目标初始化

  242. hist1 = (double *)malloc(sizeof(double)*16*16*16);

  243. m_wei = (double *)malloc(sizeof(double)*drawing_box.height*drawing_box.width);

  244. init_target(hist1, m_wei, current);

  245. is_tracking = true;

  246. break;

  247. }

  248. return;

  249. }

  250. }

  251.  
  252.  
  253.  
  254. int _tmain(int argc, _TCHAR* argv[])

  255. {

  256. CvCapture *capture=cvCreateFileCapture("test.avi");

  257. current = cvQueryFrame(capture);

  258. char res[20];

  259. int nframe = 0;

  260.  
  261. while (1)

  262. {

  263. /* sprintf(res,"result%d.jpg",nframe);

  264. cvSaveImage(res,current);

  265. nframe++;*/

  266. if(is_tracking)

  267. {

  268. MeanShift_Tracking(current);

  269. }

  270.  
  271. int c=cvWaitKey(1);

  272. //暂停

  273. if(c == 'p')

  274. {

  275. pause = true;

  276. cvSetMouseCallback( "Meanshift", onMouse, 0 );

  277. }

  278. while(pause){

  279. if(cvWaitKey(0) == 'p')

  280. pause = false;

  281. }

  282. cvShowImage("Meanshift",current);

  283. current = cvQueryFrame(capture); //抓取一帧

  284. }

  285.  
  286. cvNamedWindow("Meanshift",1);

  287. cvReleaseCapture(&capture);

  288. cvDestroyWindow("Meanshift");

  289. return 0;

  290. }


 

 

运行结果:

 

初始目标直方图:

候选目标直方图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值