代码如下:
clear all
close allclc
% 载入图片
RGB = imread('C:\Documents and Settings\Owner\桌面\Test_num.jpg');
I = rgb2gray(RGB);
se = strel('disk',50);
I2 = imbothat(I,se); % 底帽变换,去除不均匀背景
figure,imshow(I2)
I3 = imadjust(I2); % 这一步可有可无,调节灰度对比度
% 灰度图像二值化,全局阈值分割最大化类间方差
level = graythresh(I3);
BW = im2bw(I3,level);
figure,imshow(BW)
% 孔洞填充和形态学开运算
BW1 = imfill(BW,'holes');
figure,imshow(BW1)
se1 = strel('square',10);
BW2 = imopen(BW1,se1);
figure,imshow(BW2)
% 形态学腐蚀运算,部分目标物有粘连现象,去除粘连
se2 = strel('disk',15);
BW3 = imerode(BW2,se2);
figure,imshow(BW3)
% 形态学开运算,去除影响计数的干扰颗粒
se3 = strel('disk',5);
BW4 = imopen(BW3,se3);
figure,imshow(BW4)
[L,N] = bwlabel(BW4); % N即为目标个数
% 标记目标物
figure,imshow(RGB)
hold on
for k = 1:N
[r,c] = find(L == k);
rbar = mean(r);
cbar = mean(c);
plot(cbar,rbar,'marker','*','markeredgecolor','b','markersize',10);
end
% 对话框显示目标物个数
h = dialog('Name','目标个数','position',[500 500 200 70]); % 创建一个对话框窗口
uicontrol('Style','text','units','pixels','position',[45 40 120 20],...
'fontsize',15,'parent',h,'string',num2str(N)); % 创建文本内容
uicontrol('units','pixels','position',[80 10 50 20],'fontsize',10,...
'parent',h,'string','确定','callback','delete(gcf)'); % 创建【确定】按钮