Switch to unified view

a b/combinedDeepLearningActiveContour/functions/polygonCentroid.m
1
function [centroid area] = polygonCentroid(varargin)
2
%POLYGONCENTROID Compute the centroid (center of mass) of a polygon
3
%
4
%   CENTROID = polygonCentroid(POLY)
5
%   CENTROID = polygonCentroid(PTX, PTY)
6
%   Computes center of mass of a polygon defined by POLY. POLY is a N-by-2
7
%   array of double containing coordinates of vertices.
8
%
9
%   [CENTROID AREA] = polygonCentroid(POLY)
10
%   Also returns the (signed) area of the polygon. 
11
%
12
%   Example
13
%     % Draws the centroid of a paper hen
14
%     x = [0 10 20  0 -10 -20 -10 -10  0];
15
%     y = [0  0 10 10  20  10  10  0 -10];
16
%     poly = [x' y'];
17
%     centro = polygonCentroid(poly);
18
%     drawPolygon(poly);
19
%     hold on; axis equal;
20
%     drawPoint(centro, 'bo');
21
% 
22
%   References
23
%   algo adapted from P. Bourke web page
24
%
25
%   See also:
26
%   polygons2d, polygonArea, drawPolygon
27
%
28
%   ---------
29
%   author : David Legland 
30
%   INRA - TPV URPOI - BIA IMASTE
31
%   created the 05/05/2004.
32
%
33
34
% Algorithme P. Bourke, vectorized version
35
36
% HISTORY
37
% 2012.02.24 vectorize code
38
39
40
% parse input arguments
41
if nargin == 1
42
    var = varargin{1};
43
    px = var(:,1);
44
    py = var(:,2);
45
elseif nargin == 2
46
    px = varargin{1};
47
    py = varargin{2};
48
end
49
50
% vertex indices
51
N = length(px);
52
iNext = [2:N 1];
53
54
% compute cross products
55
common = px .* py(iNext) - px(iNext) .* py;
56
sx = sum((px + px(iNext)) .* common);
57
sy = sum((py + py(iNext)) .* common);
58
59
% area and centroid
60
area = sum(common) / 2;
61
centroid = [sx sy] / 6 / area;
62
end