我有一个彩色图像:
然后我应用了 k-means 算法并选择了这张图片作为合适的集群:
我想使用 MATLAB 应用形态学操作,例如清理边界、填充孔和删除小对象,但这些操作仅适用于 MATLAB 中的灰度或二值图像。
我想只选择图像中间的单元格并提取轮廓作为最后一步。
代码是:
NbIm = size(names1,1);
n1 = 1;
n2 = NbIm;
for n = n1:n2
% 1- Lecture de l'image originale
ImPath1 = strcat(DirName1,ImName1(n)); % Chemin de chaque image
Im_originale = imread(char(ImPath1)); % Chargement image
% 1- Appliquer la méthode K-means pour générer TROIS classes
cform = makecform('srgb2lab');
lab_he = applycform(Im_originale,cform);
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);
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 = Im_traiter;
color(rgb_label ~= k) = 0;
segmented_images{k} = color;
end
C1=segmented_images{1};
C2=segmented_images{2};
C3=segmented_images{3};
% 2- Selectionner la classe à traiter
[m ind]=min(cluster_center);
ClusterChoix=ind;
Im1_traiter=segmented_images{ClusterChoix};
end