文档视界 最新最全的文档下载
当前位置:文档视界 › kmeans-图像分割代码

kmeans-图像分割代码

kmeans-图像分割代码
kmeans-图像分割代码

he = imread('02.png'); % 读入图像

imshow(he), title('H&E image');

text(size(he,2),size(he,1)+15,...

'Image courtesy of Alan Partin, Johns Hopkins University', ...

'FontSize',7,'HorizontalAlignment','right');

cform = makecform('srgb2lab'); % 色彩空间转换

lab_he = applycform(he,cform);

ab = double(lab_he(:,:,2:3)); % 数据类型转换

nrows = size(ab,1); % 求矩阵尺寸

ncols = size(ab,2); % 求矩阵尺寸

ab = reshape(ab,nrows*ncols,2); % 矩阵形状变换

nColors = 3;

% 重复聚类3次,以避免局部最小值

[cluster_idxcluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates',3);

pixel_labels = reshape(cluster_idx,nrows,ncols); % 矩阵形状改变

imshow(pixel_labels,[]); % 显示图像

title('image labeled by cluster index'); % 设置图像标题

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'); % 设置图像标题

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)); % 图像黑白转换nuclei_labels = repmat(uint8(0),[nrowsncols]); % 矩阵平铺

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'); % 显示处理后的图像

相关文档