Find the centroid of any shape
30 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Phantom.i7
il 6 Set 2015
Commentato: Image Analyst
il 8 Set 2015
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
0 Commenti
Risposta accettata
Image Analyst
il 6 Set 2015
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?
2 Commenti
Image Analyst
il 8 Set 2015
Well if you do a straight line distance, then yes. You can use my attached demo to find the points farthest apart. Then calculate the distance from every point in the binary shape to that pair of points. Select the pair where the distances are closest to each other.
However, that method may allow the straight line distance to leave the shape if it's a really irregular shape. If you want the path to stay completely within the shape, then you should read Steve's blog: http://blogs.mathworks.com/steve/2011/11/01/exploring-shortest-paths-part-1/. Note that there is no guarantee that it will follow the skeleton of the image, so for a banana shape, the path may touch the inside corner of the banana rather than go through the centerline.
I don't have any code that does exactly what you want so you're going to have to adapt either Steve or my code yourself. Good luck.
Più risposte (0)
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!