MATLAB: Centroid of polyarea

centroidpolyarea

How to get a centroid of polyarea?
Here is my code.
Thanks.
figure, imshow('000445.png')
hold on
xy = [];
n = 0;
but = 1;
while but == 1
[xi,yi,but] = ginput(1);
plot(xi,yi,'r.')
n = n+1;
xy(:,n) = [xi;yi];
end
t = 1:n;
ts = 1: 0.1: n;
xys = spline(t,xy,ts);
plot(xys(1,:),xys(2,:),'r-');
A = polyarea(xys(1,:),xys(2,:));
plot(xys(1,:),xys(2,:),'r-');
title (['Area = ' num2str(A)]);
axis image
hold off

Best Answer

Hi,
I modified your first code becomes :
I = imread('peppers.png');
[r c o] = size(I);
imshow(I); hold on;
xy = [];
n = 0;
but = 1;
while but == 1
[xi, yi, but] = ginput(1);
plot(xi, yi, 'r.');
n = n + 1;
xy(:, n) = [xi; yi];
end
t = 1 : n;
ts = 1 : 0.1 : n;
xys = spline(t, xy, ts);
plot(xys(1,:), xys(2,:), 'r-');
A = polyarea(xys(1,:), xys(2,:));
plot(xys(1,:), xys(2,:), 'r-');
title (['Area = ' num2str(A)]);
axis image
%hold off
Then, I create my own code.
J = logical(zeros(r, c));
xcoor = floor(xys(1,:));
ycoor = floor(xys(2,:));
for x = 1 : numel(xcoor)
J(ycoor(x),xcoor(x)) = 1;
end
J = imdilate(J,strel('square',20));
J = bwmorph(J,'thin',inf);
J = imfill(J,'holes');
stat = regionprops(J,'Centroid');
plot(stat.Centroid(1),stat.Centroid(2),'go',...
'markerfacecolor','b')
And the result is :