1,获取图片
clear all;
clc;
im=imread(‘coin.jpg’);
2,灰度化,并且进行均值滤波
imm = rgb2gray(im);
%均值滤波
imgray=filter2(fspecial(‘average’,5),imm)/255;
3,腐蚀膨胀减运算
%腐蚀膨胀相减弱化背景
ele=strel(‘rectangle’,[5,5]);
im1=imerode(imgray,ele);
im2=imdilate(im1,ele);
im3 = imgray - im2;
4,二值化
imbw = im3 >= 0.03;
%去除小区域
im4=bwareaopen(imbw,20);
%开闭运算形态学处理
ele=strel(‘rectangle’,[10,10]);
im2=imdilate(im4,ele);
im4=bwareaopen(im2,50);
im1=imerode(im4,ele);
%填充孔洞
im2 = imfill(im1,’holes’);
im3=imerode(im2,ele);
im4=bwareaopen(im3,50);
im5=imdilate(im4,ele);
5,获得连通区域中心
L = bwlabel(im5);
s = regionprops(L, ‘centroid’);
centroids = cat(1, s.Centroid);
6,得到坐标进行下一步运算
p=ceil(centroids);
%好像图像宽为第二列,高为第一列
x=p(:,2);
y=p(:,1);
7,获得每个连通区域半径
len = zeros(2,length(x));
for i = 1 : length(x)
j = 0;
while (im5(x(i),y(i)+j) > 0)
j = j+1;
end
len(2,i) = j;
j = 0;
while (im5(x(i)+j,y(i)) > 0)
j = j+1;
end
len(1,i) = j;
end
8,去掉小区域,小于最大半径一半的认为可以去掉
maxlen = max(max(len));
for i = 1:length(len)
if len(1,i) < maxlen*0.5 || len(2,i) < maxlen*0.5
len(1,i) = 0;
len(2,i) = 0;
end
end
9,得到坐标与半径
pos = zeros(1,3);
for i = 1:length(len)
if abs(len(1,i) - len(2,i)) < 0.1 * len(1,i)
pos = [pos;x(i),y(i),(len(1,i) + len(2,i)) / 2];
end
end
10,显示图片,画出目标区域
imshow(im);
% hold on
% plot(centroids(:,1), centroids(:,2), ‘r+’)
% hold off
for i = 2:length(pos)
hold on;
rectangle(‘Position’,[pos(i,2)-pos(i,3),pos(i,1)-pos(i,3),pos(i,3)*2,pos(i,3)*2],’Curvature’,[1,1],’edgecolor’,’r’,’linewidth’,2);
% hold off;
end