-1

I am using contourf function with binary image. I am trouble how i can get the area and centroid of the different surface in the image, need this task to classify the objects.

1 Answers1

1

You need to use the the Contour Matrix output

Here is an example:

function data = ContourInfo(C)

data = [];

if isempty(C)
    return
end

k = 1;
j = 1;
while j < size(C,2);
    data(k).numxy = C(2,j);
    data(k).x = C(1,j+1:j+data(k).numxy);
    data(k).y = C(2,j+1:j+data(k).numxy);
    data(k).level = C(1,j);

    [data(k).centroid(1) data(k).centroid(2) data(k).area] = ... 
          polycentroid(data(k).x, data(k).y);
    data(k).area = polyarea(data(k).x, data(k).y);
    data(k).centroid = polycentroid(data(k).x, data(k).y);

    j = j + data(k).numxy + 1;
    k = k+1;
end

function [x0,y0,a] = polycentroid(x,y)

[m1,n1] = size(x); [m2,n2] = size(y);
n = max(m1,n1);
x = x(:); y = y(:);
x2 = [x(2:n);x(1)];
y2 = [y(2:n);y(1)];
a = 1/2*sum (x.*y2-x2.*y);
x0 = 1/6*sum((x.*y2-x2.*y).*(x+x2))/a;
y0 = 1/6*sum((x.*y2-x2.*y).*(y+y2))/a;

Call as follow:

Z = peaks(20);
[C, h] = contourf(Z,10);
contourData = ContourInfo(C)

disp('Area of contour 1:');
disp(contourData(1).area
disp('Centroid of contour 1:');
disp(contourData(1).centroid);
gregswiss
  • 1,456
  • 9
  • 20