MATLAB Answers

Error when trying to create a loop for k-means

2 views (last 30 days)
Hi all,
I'm trying to loop for a given value of k for a k-means segmentation. The following is the documentation code:
mask1 = pixelLabels==1;
cluster1 = img .*uint8(mask1);
imshow(cluster1)
title ('Objects in Cluster 1');
mask2 = pixelLabels==2;
cluster2 = img .* uint8(mask2);
imshow(cluster2)
title('Objects in Cluster 2');
mask3 = pixelLabels==3;
cluster3 = img .* uint8(mask3);
imshow(cluster3)
title('Objects in Cluster 3');
And this is my attempt at turning it into a loop:
imshow(pixelLabels,[])
title('Image Labeled by Cluster Index');
for i = 1 : k
maskID = strcat('mask', k);
clusterID = strcat('cluster', k);
maskID = pixelLabels == k
clusterID = img.*uint8(maskID);
imshow(clusterID)
title('Objects in Cluster ', num2str(clusterID));
end
I not only get an error (incorrect number of arguments) but I also get an incorrect output (only 1 black image).
Any help would be much appreciated!

  0 Comments

Sign in to comment.

Accepted Answer

KALYAN ACHARJYA
KALYAN ACHARJYA on 22 Jan 2020
Edited: KALYAN ACHARJYA on 22 Jan 2020
%Defined
img=
pixelLabels=
k=
for i = 1 : k
maskID = strcat('mask', 1);
clusterID = strcat('cluster', 1);
maskID = pixelLabels == k
clusterID = img.*uint8(maskID);
imshow(clusterID)
title(['Objects in Cluster ',num2str(i)]);
end

  2 Comments

Teshan Rezel
Teshan Rezel on 22 Jan 2020
thanks, this seems to work! Do you know how I can plot each figure seperately, once each iteration of the loop ends please?
KALYAN ACHARJYA
KALYAN ACHARJYA on 22 Jan 2020
%Defined
img=
pixelLabels=
k=
for i = 1 : k
maskID = strcat('mask', 1);
clusterID = strcat('cluster', 1);
maskID = pixelLabels == k
clusterID = img.*uint8(maskID);
figure,imshow(clusterID); % Figure here
title(['Objects in Cluster ',num2str(i)]);
end

Sign in to comment.

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!