clc
[fname,pname,index] = uigetfile({'*.jpg';'*.bmp'},'选择图片');
str = [pname fname];
gray_img= imread(str);
mainfc;
bw_img=gray_img<200;
bw_img=~bw_img;
figure(1)
subplot(121),imshow(gray_img);title('原图');
subplot(122),imshow(bw_img);title('初步定位图');
se=strel('disk',30);
img2=imdilate(bw_img,se);
figure(2);imshow(img2);title('膨胀运算');
%%去除最小面积
img4=bwareaopen(img2,10000); %%%去除面积大于10000的像素块,bw为二值图
figure(3)
imshow(img4);
title('去除最小面积');
%%显示缺陷
Img = gray_img .* uint8(img4);
figure(4)
imshow(Img);
title('留下定位到的区域图');
%%%定位计数
L = bwlabel(img4);%默认8连通; bwlabe(bw,4);
STATS = regionprops(L,'all');%STATS中含有所有连通域的properations
%在bw图像上绘制出连通域的矩形框
figure(5); imshow(gray_img); title('定位图')
hold on
for i = 1 : size(STATS, 1)
boundary = STATS(i).BoundingBox;
rectangle('Position',boundary,'edgecolor','r' );
end