基于K-Means的彩色图像分割
下面的例子将展示如何通过K-Means和Lab颜色空间的彩色图像分割。
首先读入图片,下图显示了一张用血毒素和伊红(H&E)染色的组织图像。这种染色方法有助于病理学家区分不同的组织类 型。
如果忽略亮度的变化,你可以从上图中观察到多少种颜色?显然,你可以轻易的观察到红色,蓝色和粉色。而Lab颜色空间可以准确的定量这些颜色变化。
下面使用makecform() 和 applycform() 函数将原图从RGB空间转到LAB:
cform = makecform('srgb2lab');
lab_he = applycform(he,cform);
K-Means聚类关注空间中每个物体的位置。它试图使得每个类别的物体尽可能的接近,而不同类别的物体尽可能的远。K-Means算法需要用户指定类别数量以及一个衡量距离的方法。
由于颜色信息存在于AB颜色空间,下面使用欧式距离度量方法将原图的像素分为3个类别:
ab = double(lab_he(:,:,2:3));
nrows = size(ab,1);
ncols = size(ab,2);
ab = reshape(ab,nrows*ncols,2);
nColors = 3;
% repeat the clustering 3 times to avoid local minima
[cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ...
'Replicates',3);
kmeans()函数对每个输入像素均返回一个属于哪个类别的索引以及聚类中心位置信息。
pixel_labels = reshape(cluster_idx,nrows,ncols);
imshow(pixel_labels,[]), title('image labeled by cluster index');
得到的pixel_labels 矩阵和原图行列数相同,其数值代表了像素的分类结果。如:pixel_labels (1,1)=3表示该像素属于第三类。
显然,通过pixel_labels矩阵可以显示原图分割为3个类别的结果。
segmented_images = cell(1,3);
rgb_label = repmat(pixel_labels,[1 1 3]);
for k = 1:nColors
color = he;
color(rgb_label ~= k) = 0;
segmented_images{k} = color;
end
imshow(segmented_images{1}), title('objects in cluster 1');
显示第二类分割结果:
imshow(segmented_images{2}), title('objects in cluster 2');
显示第三类:
imshow(segmented_images{3}), title('objects in cluster 3');
注意到这里的深蓝色和亮蓝色属于了同一个类别,使用LAB颜色空间可将其分开。而细胞核属于深蓝色。
L层包含了每种颜色的亮度信息。寻找到蓝色类别,然后提取此类的亮度值然后使用im2bw()函数将其二值化。
你必须通过代码来确定蓝色是哪一个类别,因为kmeans()函数不会在每次都返回相同的聚类编号。
你可以通过’a*’,‘b*’ 均值来确定,蓝色类别有最小的cluster_center值。
mean_cluster_value = mean(cluster_center,2);
[tmp, idx] = sort(mean_cluster_value);
blue_cluster_num = idx(1);
L = lab_he(:,:,1);
blue_idx = find(pixel_labels == blue_cluster_num);
L_blue = L(blue_idx);
is_light_blue = im2bw(L_blue,graythresh(L_blue));
通过is_light_blue来确定是否属于深蓝色。下图显示了分割效果:
nuclei_labels = repmat(uint8(0),[nrows ncols]);
nuclei_labels(blue_idx(is_light_blue==false)) = 1;
nuclei_labels = repmat(nuclei_labels,[1 1 3]);
blue_nuclei = he;
blue_nuclei(nuclei_labels ~= 1) = 0;
imshow(blue_nuclei), title('blue nuclei');