MATLAB运动目标检测代码.docx
精选优质文档-倾情为你奉上运动目标检测matlab程序:clearclcnStar = 1;nNUM = 164;Background = double( rgb2gray(imread( 'car (',int2str(nStar),').bmp') );%第一帧当做初始背景% 背景更新过程,其中int2str将整型常量转为字符串for k = nStar+1 :1: nNUM CurrentImage =double(rgb2gray(imread( 'car (',int2str(k),').bmp' ); % 当前帧 FormerImage =double(rgb2gray(imread( 'car (',int2str(k-1),').bmp' ); % 前一帧 ID =uint8(abs( CurrentImage - FormerImage ); % 帧间差分 % 选择阈值 T=yuzhi(ID); %迭代法计算二值化阈值,比较耗时 BW = im2bw(ID,T/255); % 更新背景 alpha = 0.1; %背景更新的速度 CurrentBack = Background.*BW + ( alpha.* CurrentImage + ( 1-alpha ).* Background ).*( 1 -BW );%前后两帧有变化的区域不更新,无变化的区域更新到背景中去 Background = CurrentBack;%背景更新完毕 Cut=abs(CurrentImage-Background);%前景与背景差分 Cut=uint8(Cut); Tcut=yuzhi(Cut);%迭代法计算二值化阈值,比较耗时 BWCut=im2bw(Cut,Tcut/255);%差分后的图像进行二值化 SE=1 1 1;1 1 1;1 1 1;%结构元素 BWCutero=imerode(BWCut,SE);%对二值图像进行腐蚀,以消除微小变动的区域 BWCuterodil = bwmorph(BWCutero,'dilate',3);%膨胀 figure(1),imshow(BWCuterodil),title('差分后的二值化图像') figure(2),imshow(imread( 'car (',int2str(k),').bmp' ) L,nm = bwlabel(BWCuterodil,8);%找出图像中的八连通区域,视为车辆所在的区域 for i = 1:nm r,c = find(L = i); left= min(c); right= max(c); top= min(r); buttom= max(r); width=right - left + 1; height = buttom - top + 1; rectangle('Position',left,top,width,height,'EdgeColor','r');%对车辆用矩形标记pause(0.01); endend%用来计算灰度图像二值化时的阈值,采用迭代法function m=yuzhi(Imgray)mingray=min(min(Imgray);maxgray=max(max(Imgray);m=double(mingray)/2+double(maxgray)/2; %初始分割阈值while 1a=find(Imgray<=m);A=sum(Imgray(a)/length(a);b=find(Imgray>m);B=sum(Imgray(b)/length(b);n=(A+B)/2;if abs(m-n)<1 break;else m=n;endend专心-专注-专业