Search code examples
matlabplotcentroid

Add centroid to plot - Matlab


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

Solution

  • 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);
    

    Explanation

    stat(k) will get the kth 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).


    Alternative Improvements

    Some improvements to your code that I would suggest are

    • Put close all at the top of the script. This will close all currently open figures
    • Add figure; hold on; before the for loop and remove hold on from within the for loop. Calling hold on; multiple times is redundant.