Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Calculate area of polygon area with holes
Date: Fri, 31 Jul 2009 06:46:05 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 50
Message-ID: <h4u3vd$5mc$1@fred.mathworks.com>
References: <h0oll9$r0s$1@fred.mathworks.com> <h0ouvg$gja$1@fred.mathworks.com> <h0p79m$21s$1@fred.mathworks.com> <h4t02f$ijh$1@fred.mathworks.com>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1249022765 5836 172.30.248.37 (31 Jul 2009 06:46:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 31 Jul 2009 06:46:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:559834


"Naresh Pai" <npai@uark.edu> wrote in message <h4t02f$ijh$1@fred.mathworks.com>...
> Hi Bruno,
>       I was reading one of your posts on mathworks. I have a similar issue where I would like to calculate the area of a polygon which as holes in it. The polyarea function seems to count this area too. Is there a work around ?
> 
> Naresh
> 


If you have the array of vertexes *properly* ordered: i.e., going around the area where the polygon is always located on the left side, jumping from one (external) contour to another (internal) contour is allowed (but you must ensure going in and out always through the same pair of vertices), you can also apply the algebric area formula (see bellow). It would remove the hole area properly.

I don't know how CONTOUR function returns the contours, but I once write my own contour function where the result oriented correctly with respect to the sign of the function, which is great to compute areas even with hole (I solve some level-set problem IIRC).

The bottom line is compute the area with hole is not hard, what is hard is order properly the vertices.

Bruno

function a=carea(cx, cy)
% function a=carea(cx, cy); OR
% function a=carea(c);
%
% PURPOSE: returns the algebric area of a contour line
%          carea returns a>0 for contour that is counterclockwise oriented
%                        a<0 otherwise
% INPUT: c (n x 2)-vector of coordinates of the polygonal vertex
%          if the number of vertex n is not equal to n, then input
%          c of dimension (2 x n) is also alright
%        cx, cy: passing x and y-coordinates separately
%

if ~isempty(cx)
    if nargin>=2
      if size(cx,1)~=1
        cx=cx';
      end
      if size(cy,1)~=1
        cy=cy';
      end
      x=[cx cx(1)];
      y=[cy cy(1)];        
    else
      if size(cx,2)~=2
          cx=cx';
      end
      x=[cx(:,1); cx(1,1)];
      y=[cx(:,2); cx(1,2)];
    end
    a=sum((x(1:end-1)-x(2:end)).*(y(1:end-1)+y(2:end)))/2;
else
    a=0;
end