K均值聚类、分水岭算法计算图片中红白细胞个数
K均值聚类
1、任取[0,255]中K个值作为第一次分类中心
2、把图像(gray)中的每一个点与K个中心值进行比较,按差值分成K组,求出新的K个中心点
3、重复上一步骤直到前后两次算出的中心点值相同
4、按最后得到的中心点把图像依据点到中心点的距离分成K类。
程序
function [cen,copy]=Kmeans(I,k) % K均值聚类函数
mm=max(max(I)); % mm为I的最大灰度值
copy=I;
cen=(1:k)*mm/k; % 求出首次中心值
cen1=zeros(1,k);
d=ones(1,k)./255;
[m,n]=size(I);
J=zeros(m,n);
while(1)
for i=1:m
for j=1:n
c=abs(I(i,j)-cen); % c为I中元素与各中心点的差值数组
cc=find(min(c)==c); % cc为距中心值最近的元素下标
J(i,j)=cc;
end
end
% 求新的中心点
for r=1:k
h=0;
[J1,J2]=find(J==r);
p=length(J1);
for s=1:p
h=h+I(J1(s),J2(s));
copy(J1(s),J2(s))=cen(r); % 按中心值把原图像灰度分为K类
end
cen1(r)=h/p;
end
if (abs(cen1-cen)<=d)
break;
else cen=cen1;
end
end
K均值聚类、分水岭算法总程序
I=imread('blood.jpg'); % 读入处理图像
R=I(:,:,1); % 分离R分量
G=I(:,:,2);
B=I(:,:,3);
clc; % 清屏
close all; % 关闭图像窗口
figure, % 开辟图像显示窗口
subplot(2,3,1),imshow(R),title('R分量');
subplot(2,3,2),imshow(G),title('G分量');
subplot(2,3,3),imshow(B),title('B分量');
K=rgb2hsv(I); % RGB图像转换成HSV图像
H=K(:,:,1);
S=K(:,:,2);
V=K(:,:,3);
subplot(2,3,4),imshow(H),title('H分量');
subplot(2,3,5),imshow(S),title('S分量');
subplot(2,3,6),imshow(V),title('V分量');
%****************************** 白细胞计数 ******************************%
% 分割出只有白细胞的二值图像
[cenwhite,copywhite]=Kmeans(H,3); % K均值聚类函数调用
cenwhite; % 查看聚类后的中心值
figure,
subplot(1,3,1),imshow(copywhite,[ ]),title('H分量K均值聚类结果');
A=copywhite;
[m,n]=size(A); % 把聚类后图像二值化
for i=1:m
for j=1:n
if A(i,j)==cenwhite(2)
A(i,j)=1;
else A(i,j)=0;
end
end
end
subplot(1,3,2),imshow(A,[ ]),title('白细胞二值化结果');
C1=imdilate(A,ones(5)); % 对二值化图