Centroid of polyarea
3 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Chandra Kurniawan
on 9 Jan 2012
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 :
2 Comments
Sean de Wolski
on 9 Jan 2012
You could use poly2mask() instead of the dilation/skeletonization. I do not believe the method you are using would be correct at boundaries. I.e. where the strel is not fully represented on boundary of the image, the thinning operation will be shifted in and not centered since the strel was not centered at the edge.
Though regionprops/works for this, in two dimensions the formula is well defined:
http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon
More Answers (1)
Sean de Wolski
on 9 Jan 2012
Once you know area, A, and coordinates: x, y:
As = sum(A)/2;
x_bar = (sum((x(2:end)+x(1:end-1)).*A)*1/6)/As;
y_bar = (sum((y(2:end)+y(1:end-1)).*A)*1/6)/As;
2 Comments
THAMMISHETTI NIKESH
on 12 Nov 2012
x=[0 10 10 12 12 20 20 12 10 8 8 0 0]; y=[3 3 0 0 3 3 6 6 20 20 6 6 3]; As=polyarea(x,y); X_bar=0; Y_bar=0; h=length(x)-1; for a=1:h X_bar=(1/(6*As))*(x(a)+x(a+1))*(x(a)*y(a+1)-x(a+1)*y(a))+X_bar; Y_bar=(1/(6*As))*(y(a)+y(a+1))*(x(a)*y(a+1)-x(a+1)*y(a))+Y_bar; end
I used the above code, hope it helps you
See Also
Categories
Find more on Data Exploration in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!