MeanShift运动目标跟踪matlab程序思路简介:1.截取跟踪目标矩阵rect2.求取跟踪目标的加权直方图hist13.读取视频序列中的一帧,先随机取一块与rect等大的矩形,计算加权直方图hist2。4.计算两者比重函数,如果后者差距过大,更新新的矩阵中心Y,进行迭代(MeanShift是一种变步长可以迅速接近概率密度峰值的方法),直至一定条件后停止。源程序(参考过其他程序):[plain]viewplaincopy1.function[]=select()closeall;clearall;%%%%%%%%%%%%%%%%%%根据一幅目标全可见的图像圈定跟踪目标%%%%%%%%%%%%%%%%%%%%%%%I=imread('E:\数字图像处理\6\2\18.bmp');figure(1);imshow(I);[temp,rect]=imcrop(I);[a,b,c]=size(temp);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%计算目标图像的权值矩阵%%%%%%%%%%%%%%%%%%%%%%%y(1)=a/2;y(2)=b/2;tic_x=rect(1)+rect(3)/2;tic_y=rect(2)+rect(4)/2;m_wei=zeros(a,b);%权值矩阵h=y(1)^2+y(2)^2;%带宽fori=1:aforj=1:bdist=(i-y(1))^2+(j-y(2))^2;m_wei(i,j)=1-dist/h;%epanechnikovprofileendendC=1/sum(sum(m_wei));%归一化系数%计算目标权值直方图qu%hist1=C*wei_hist(temp,m_wei,a,b);%targetmodelhist1=zeros(1,a*b);fori=1:aforj=1:b%rgb颜色空间量化为16*16*16binsq_r=fix(double(temp(i,j,1))/16);%fix为趋近0取整函数q_g=fix(double(temp(i,j,2))/16);q_b=fix(double(temp(i,j,3))/16);q_temp=q_r*256+q_g*16+q_b;%设置每个像素点红色、绿色、蓝色分量所占比重hist1(q_temp+1)=hist1(q_temp+1)+m_wei(i,j);%计算直方图统计中每个像素点占的权重endendhist1=hist1*C;rect(3)=ceil(rect(3));rect(4)=ceil(rect(4));%%%%%%%%%%%%%%%%%%%%%%%%%读取序列图像myfile=dir('*.bmp');lengthfile=length(myfile);forl=1:lengthfileIm=imread(myfile(l).name);num=0;Y=[2,2];%%%%%%%meanshift迭代while((Y(1)^2+Y(2)^20.5)&num20)%迭代条件num=num+1;temp1=imcrop(Im,rect);%计算侯选区域直方图%hist2=C*wei_hist(temp1,m_wei,a,b);%targetcandidatespuhist2=zeros(1,a*b);fori=1:aforj=1:bq_r=fix(double(temp1(i,j,1))/16);q_g=fix(double(temp1(i,j,2))/16);q_b=fix(double(temp1(i,j,3))/16);q_temp1(i,j)=q_r*256+q_g*16+q_b;hist2(q_temp1(i,j)+1)=hist2(q_temp1(i,j)+1)+m_wei(i,j);endendhist2=hist2*C;figure(2);subplot(1,2,1);plot(hist2);holdon;w=zeros(1,a*b);fori=1:a*bif(hist2(i)~=0)w(i)=sqrt(hist1(i)/hist2(i));elsew(i)=0;endend%变量初始化sum_w=0;xw=[0,0];fori=1:a;forj=1:bsum_w=sum_w+w(uint32(q_temp1(i,j))+1);xw=xw+w(uint32(q_temp1(i,j))+1)*[i-y(1)-0.5,j-y(2)-0.5];endendY=xw/sum_w;%中心点位置更新rect(1)=rect(1)+Y(2);rect(2)=rect(2)+Y(1);end%%%跟踪轨迹矩阵%%%tic_x=[tic_x;rect(1)+rect(3)/2];tic_y=[tic_y;rect(2)+rect(4)/2];v1=rect(1);v2=rect(2);v3=rect(3);v4=rect(4);%%%显示跟踪结果%%%subplot(1,2,2);imshow(uint8(Im));title('目标跟踪结果及其运动轨迹');holdon;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');plot(tic_x,tic_y,'LineWidth',2,'Color','b');end结果截图: