In the following script I get the coordinates of and coins in an image, later they are plotted. How can I also add to the plot the centroid calculated using stat (in red, marked as X)?
Script:
clc;
clear;
I = imread('coins.png');
imshow(I)
BW = im2bw(I);
BW_filled = imfill(BW,'holes');
stat = regionprops(BW_filled,'centroid');
boundaries = bwboundaries(BW_filled);
for k=1:10
b = boundaries{k};
plot(b(:,2),b(:,1),'g','LineWidth',3);
hold on;
end
Add
plot(stat(k).Centroid(1), stat(k).Centroid(2), 'rx');
after
plot(b(:,2), b(:,1), 'g', 'LineWidth', 3);
hold on;
You can also apply any additional customisations to the centroid point like
plot(stat(k).Centroid(1), stat(k).Centroid(2), 'rx', 'LineWidth', 3);
stat(k)
will get the k
th element of stat
. stat(k).Centroid
will extract the centroid as [x, y]
and we can then reference the x
coordinate of the centroid as stat(k).Centroid(1)
and the y
as stat(k).Centroid(2)
.
Some improvements to your code that I would suggest are
close all
at the top of the script. This will close all currently open figuresfigure; hold on;
before the for
loop and remove hold on
from within the for
loop. Calling hold on;
multiple times is redundant.