clc;%清空变量
mainfc;
c=imread('streetcar1.jpg');%车子图片
streetcar=c;%赋值
b=imread('street.jpg');%街景,背景图
figure(1);
subplot(231);
imshow(c);%显示原图
title('原图');
subplot(232);
c=imsubtract(c,b);%相减
imshow(c);
title('作差图');
%将待识别图像与背景图像进行比较,识别出车子,并只留下车子
for i=1:600 %从第1到600行
for j=1:800 %从1-800列
if (abs(double(b(i,j,1))-double(streetcar(i,j,1)))>2) %b(i,j,1)表示H通道 ,b(i,j,2)表示 S通道,b(i,j,3)表示V通道
c(i,j,1)=0;%每个通道 的 像素相同,那么变为黑色,否则 为白色
c(i,j,2)=0;
c(i,j,3)=0;
elseif (abs(double(b(i,j,2))-double(streetcar(i,j,2)))>2)
c(i,j,1)=0;
c(i,j,2)=0;
c(i,j,3)=0;
elseif (abs(double(b(i,j,3))-double(streetcar(i,j,3)))>2)
c(i,j,1)=0;
c(i,j,2)=0;
c(i,j,3)=0;
else
c(i,j,1)=255;
c(i,j,2)=255;
c(i,j,3)=255;
end
end
end
%图像处理,包括灰度化,二值化和腐蚀,去除噪声
%c=imcomplement(c)
%c=immultiply(a,c);
c=rgb2gray(c);%c是 经过上述 hsv通道处理作差后的彩色图象
leftcar=dither(c);
subplot(233);
imshow(leftcar);
title('车子轮廓初步定位');
leftcar=~leftcar;%取反
subplot(234);
imshow(leftcar);
title('反色处理');
leftcar=bwmorph(leftcar,'erode',1);
leftcar=~leftcar;
%leftcar=bwmorph(leftcar,'erode',5);
leftcar=~leftcar;
vsumleftcar=sum(leftcar,2);
%找到车棚,并得到宽度
for i=1:599
if (vsumleftcar(i)<80) & (vsumleftcar(i+1)>80)
top=i;
break;
end
end
for i=1:599
if (vsumleftcar(600-i)<80) & (vsumleftcar(599-i)>80)
bottom=600-i;
break;
end
end
topvalue=vsumleftcar(bottom-ceil((bottom-top)*4/5));
bottomvalue=vsumleftcar(bottom-ceil((bottom-top)*2/5));
maxvalue=max(vsumleftcar);
percent=topvalue/maxvalue;
subplot(235);
imshow(~leftcar);
title('车子轮廓');
h=findobj(gcf,'Tag','text2');
%根据判断依据确定车型
if (percent>=0.2) & (percent<=0.5)
str1=sprintf('小汽车\n\n');
str2=num2str(percent);
string=[str1 '高宽比:' str2];
msgbox(string,'温馨提示','none');
return
end