k 表示 matlab 中的代码
k means code in matlab
所以我有这个代码:
for i = 1:38
he = cores{i,1};
imshow(he), title('H&E image');
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;
% 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);
figure;
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
figure
imshow(segmented_images{1}), title('objects in cluster 1');
figure
imshow(segmented_images{2}), title('objects in cluster 2');
figure
imshow(segmented_images{3}), title('objects in cluster 3');
end
我有 38 张不同的图像,有棕色、蓝色和绿色。我想用 3 个不同的变量来区分它们,这就是这段代码所做的。
唯一的问题是我需要知道哪个是哪个(例如,第一个单元格始终是蓝色,第二个单元格始终是棕色,最后一个单元格是绿色)但通常我会以随机顺序获取它们。
有什么想法吗?
k-means 算法需要开始猜测质心的位置,这通常是随机选择的。如果问题的表述合理,起点的选择不会影响最终结果,只是标签的顺序可能不同,这就是您所看到的。
您可以考虑自己定义起点,消除每次要打乱的结束标签的随机性。 Matlab 的 k-means 算法允许您通过将起点传递给“Start”参数来执行此操作。 here.
给出了如何完成的示例
如果您希望质心对应于棕色、蓝色和绿色,我建议将这些的 rgb 值作为起始质心传递。您应该意识到,您可能会不幸地选择不会收敛到您满意的解决方案的起始质心:如果是这样,请稍微改变您的猜测!
所以我有这个代码:
for i = 1:38
he = cores{i,1};
imshow(he), title('H&E image');
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;
% 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);
figure;
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
figure
imshow(segmented_images{1}), title('objects in cluster 1');
figure
imshow(segmented_images{2}), title('objects in cluster 2');
figure
imshow(segmented_images{3}), title('objects in cluster 3');
end
我有 38 张不同的图像,有棕色、蓝色和绿色。我想用 3 个不同的变量来区分它们,这就是这段代码所做的。
唯一的问题是我需要知道哪个是哪个(例如,第一个单元格始终是蓝色,第二个单元格始终是棕色,最后一个单元格是绿色)但通常我会以随机顺序获取它们。
有什么想法吗?
k-means 算法需要开始猜测质心的位置,这通常是随机选择的。如果问题的表述合理,起点的选择不会影响最终结果,只是标签的顺序可能不同,这就是您所看到的。
您可以考虑自己定义起点,消除每次要打乱的结束标签的随机性。 Matlab 的 k-means 算法允许您通过将起点传递给“Start”参数来执行此操作。 here.
给出了如何完成的示例如果您希望质心对应于棕色、蓝色和绿色,我建议将这些的 rgb 值作为起始质心传递。您应该意识到,您可能会不幸地选择不会收敛到您满意的解决方案的起始质心:如果是这样,请稍微改变您的猜测!