# How to display a polygon and its centroid

4 vues (au cours des 30 derniers jours)
ISABELLE GUNDRUM le 7 Mar 2022
I am using this code to draw polygons on an image, but I am unsure of how to later display the drawn polygon and centroid on the image. Any suggestions?
My code:
for k=1:3
c{k} = zeros(1,3);
end
for k = 1:3
tmp = input(['Press any key to draw Polygon # ' int2str(k) ': ']);
close all, imshow(I), title(['Polygon # ' int2str(k)])
h = drawpolygon;
% The vertices of k-th polygon is recorded in polyin{k}
polyin{k} = polyshape(h.Position); % create a polygon object
[cx,cy] = centroid(polyin{k});
c{k}(1:2) = round([cx cy],0); % unit: pixels
c{k}(3) = round(area(polyin{k}),0)*p2cm; % unit: cm^2
if k==3
tmp = input('Press any key to complete.')
end
disp(['Centroid of polygon: [' int2str([cx cy]) ']'])
disp(['Area of polygon = ' int2str(c{k}(3)) 'cm^2'])
end
Thanks!
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Matt J le 7 Mar 2022
Modifié(e) : Matt J le 7 Mar 2022
close all, imshow(I),
for k = 1:3
title(['Polygon # ' int2str(k)]);
h = drawpolygon;
wait(h);
centroid=mean(h.Position);
drawpoint('Position',centroid,'Label','Centroid');
end
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Plus de réponses (1)

yanqi liu le 8 Mar 2022
p2cm = 1;
for k=1:3
c{k} = zeros(1,3);
end
for k = 1:3
tmp = input(['Press any key to draw Polygon # ' int2str(k) ': ']);
close all, imshow(I), title(['Polygon # ' int2str(k)])
h = drawpolygon;
% The vertices of k-th polygon is recorded in polyin{k}
polyin{k} = polyshape(h.Position); % create a polygon object
[cx,cy] = centroid(polyin{k});
c{k}(1:2) = round([cx cy],0); % unit: pixels
c{k}(3) = round(area(polyin{k}),0)*p2cm; % unit: cm^2
if k==3
tmp = input('Press any key to complete.')
end
disp(['Centroid of polygon: [' int2str([cx cy]) ']'])
disp(['Area of polygon = ' int2str(c{k}(3)) 'cm^2'])
pts = [h.Position; h.Position(1,:)];
delete(h);
hold on; plot(pts(:,1), pts(:,2), 'r.-', 'LineWidth',3);
plot(mean(pts(:,1)), mean(pts(:,2)), 'cp', 'MarkerFaceColor', 'c');
hold off;
end
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Elementary Polygons dans Help Center et File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!

Translated by