阈值分割
Question:
将以下A4纸上的线条单独识别出来。
Answer:
function segmentation
img=imread('input.png');
f=im2double(img);
%ãÐÖµ·Ö¸îËã·¨¡ª¡ªµü´ú·¨
T=0.5*(min(f(:))+max(f(:)));
done=false;
while ~done
g=f>=T;
Tn=0.5*(mean(f(g))+mean(f(~g)));
done=abs(T-Tn)<0.1;
T=Tn;
end
threshold=im2bw(f,T);
subplot(121),imshow(img),title('Ôͼ');
subplot(122),imshow(threshold),title('ãÐÖµ·Ö¸îËã·¨');
%ÂÖÀªÌáÈ¡
% ±ß½ç¼ì²â
%b=edge(r,'Canny',0.2);
%figure
%imshow(b);
%d=imfill(b,'hole');
%ÐÎ̬ѧͼÏñ´¦Àí¡ª¡ª¸¯Ê´
se1=strel('disk',4);
bw1=imerode(threshold,se1);
figure
imshow(bw1), title('¸¯Ê´ºóµÄͼÏñ');
%ÂÖÀªÌáÈ¡
outline = bwperim(bw1);
figure
imshow(outline);
title('ÂÖÀª')
[l,m]=bwlabel(outline,8);
status=regionprops(l,'BoundingBox');
figure
imshow(outline), title('¾ØÐÎÂÖÀªÌáÈ¡');hold on;
for i=1:m
rectangle('position',status(i).BoundingBox,'edgecolor','green');
end
%{
disp (m);
disp (status(1).BoundingBox);
disp (status(2).BoundingBox);
disp (status(3).BoundingBox);
disp (status(4).BoundingBox);
disp (status(5).BoundingBox);
disp (status(6).BoundingBox);
disp (status(7).BoundingBox);
disp (status(8).BoundingBox);
%}
output1 = imcrop(img,[status(2).BoundingBox(1),status(2).BoundingBox(2),status(2).BoundingBox(3),status(2).BoundingBox(4)]);
output2 = imcrop(img,[status(3).BoundingBox(1),status(3).BoundingBox(2),status(3).BoundingBox(3),status(3).BoundingBox(4)]);
output3 = imcrop(img,[status(4).BoundingBox(1),status(4).BoundingBox(2),status(4).BoundingBox(3),status(4).BoundingBox(4)]);
output4 = imcrop(img,[status(5).BoundingBox(1),status(5).BoundingBox(2),status(5).BoundingBox(3),status(5).BoundingBox(4)]);
output5 = imcrop(img,[status(6).BoundingBox(1),status(6).BoundingBox(2),status(6).BoundingBox(3),status(6).BoundingBox(4)]);
output6 = imcrop(img,[status(7).BoundingBox(1),status(7).BoundingBox(2),status(7).BoundingBox(3),status(7).BoundingBox(4)]);
output7 = imcrop(img,[status(8).BoundingBox(1),status(8).BoundingBox(2),status(8).BoundingBox(3),status(8).BoundingBox(4)]);
figure
imshow(output1);
figure
imshow(output2);
figure
imshow(output3);
figure
imshow(output4);
figure
imshow(output5);
figure
imshow(output6);
figure
imshow(output7);
end
Algorithm description:
1.阈值分割——迭代法
迭代法是基于逼近的思想,其步骤如下:
(1)求出图象的最大灰度值和最小灰度值,分别记为ZMAX和ZMIN,令初始阈值T0=(ZMAX+ZMIN)/2;
(2)根据阈值TK将图象分割为前景和背景,分别求出两者的平均灰度值ZO和ZB;
(3)求出新阈值TK+1=(ZO+ZB)/2;
(4)若TK=TK+1,则所得即为阈值;否则转2,迭代计算。
%阈值分割算法——迭代法
T=0.5*(min(f(:))+max(f(:)));
done=false;
while ~done
g=f>=T;
Tn=0.5*(mean(f(g))+mean(f(~g)));
done=abs(T-Tn)<0.1;
T=Tn;
end
threshold=im2bw(f,T);
2.形态学图像处理——腐蚀
%形态学图像处理——腐蚀
se1=strel('disk',4);
bw1=imerode(threshold,se1);
3.轮廓检测与提取
outline = bwperim(bw1);
figure
imshow(outline);
title('轮廓')
[l,m]=bwlabel(outline,8);
status=regionprops(l,'BoundingBox');
figure
imshow(outline), title('矩形轮廓提取');hold on;
for i=1:m
rectangle('position',status(i).BoundingBox,'edgecolor','green');
end
Result:
相关阅读
阈值分割是一种简单有效的图像分割方法,适用于分割物体与背景有较强对比的图像,所有灰度大于或等于阈值的像素被判定为属于物体,灰度