MATLAB: Find the centroid of any shape

centroidimageimage analysisimage processingImage Processing Toolboxshape

Hi, the code below finds the centroid of an image however if the shape is a crescent the output shows that the centroid is outside the shape.
clc;
close all;
clear;
workspace;
format long g;
format compact;
fontSize = 20;
grayImage = imread('c7.png');
[rows, columns, numberOfColorBands] = size(grayImage)
if numberOfColorBands > 1
grayImage = grayImage(:, :, 2);
end
subplot(2, 1, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize, 'Interpreter', 'None');
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
binaryImage = grayImage > 128;
binaryImage = imclearborder(binaryImage);
binaryImage = bwareaopen(binaryImage, 1000);
subplot(2, 1, 2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
labeledImage = bwlabel(binaryImage, 8);
blobMeasurements = regionprops(labeledImage, 'Centroid');
numberOfBlobs = size(blobMeasurements, 1);
hold on;
for k = 1 : length(blobMeasurements)
x = blobMeasurements(k).Centroid(1);
y = blobMeasurements(k).Centroid(2);
plot(x, y, 'r+', 'MarkerSize', 30, 'LineWidth', 3);
str = sprintf('The centroid of shape %d is at (%.2f, %.2f)', ...
k, x, y);
uiwait(helpdlg(str));
end

Best Answer

Of course. Yes, that is correct. As you probably know, the centroid is only guaranteed to be inside the shape if the shape is convex. For some arbitrarily irregular shape, the centroid may be inside or outside the shape. Are you just stating a fact for others who may not know this, or do you have a question?