calculate area enclosed by a loop in matlab

One possible solution is to use the regionprops function to obtain the boundary pixels of the loop and then calculate the area enclosed using Shoelace formula. Here is the code:

main.m
% Read binary image with loop
img = imread('loop.png');
bw = imbinarize(img);

% Get boundary pixels of loop
s = regionprops(bw, 'PixelList');
boundary_pixels = s.PixelList;

% Use Shoelace formula to calculate area
x = boundary_pixels(:,1);
y = boundary_pixels(:,2);
area = 1/2 * abs(sum(x.*[y(2:end);y(1)]) - sum(y.*[x(2:end);x(1)]));
337 chars
13 lines

In the first line, we read in a binary image that contains a loop. Then we use the imbinarize function to convert it to a binary image if necessary.

Next, we use regionprops to extract the list of boundary pixels of the loop. Note that we use the 'PixelList' parameter of regionprops to obtain the boundary pixels in the form of an (N x 2) matrix, where each row corresponds to the (x,y) coordinates of a boundary pixel.

Finally, we use Shoelace formula to calculate the area enclosed by the loop. The formula works as follows: Given a polygon with vertices (x1,y1), (x2,y2), ..., (xn,yn), the area enclosed by the polygon is given by

main.m
1/2 * abs(sum(x.*[y(2:end);y(1)]) - sum(y.*[x(2:end);x(1)]))
61 chars
2 lines

where x = [x1,x2,...,xn] and y = [y1,y2,...,yn]. This formula is also known as Gauss's area formula, or the surveyor's formula, or the shoestring formula.

Note that the Shoelace formula works for any simple polygon, whether it is convex or concave or self-intersecting, as long as the vertices are listed in order. However, it does not work for polygons with holes, or for polygons with degenerate edges or vertices.

gistlibby LogSnag