From: Sujit on
How can I quickly convert contours to polygons? i.e. How can I quickly extract all polygons (x and y) from C, where [C,g] = contour(Z); ?

The structure of C looks complicated -- anyone have something handy?
From: Bruno Luong on
"Sujit " <kirpekar(a)gmail.com> wrote in message <hodo49$t4u$1(a)fred.mathworks.com>...
> How can I quickly convert contours to polygons? i.e. How can I quickly extract all polygons (x and y) from C, where [C,g] = contour(Z); ?
>
> The structure of C looks complicated -- anyone have something handy?

A = peaks(40);
v=[-10:10]

c = contourc(A, v);
struct = contour2poly(c)

%%
function cstruct = contour2poly(c)

idxlabel = 1;
l = 1;
cstruct = struct('level', {}, 'x', {}, 'y', {});
while idxlabel <= size(c,2)
n = c(2,idxlabel);
cstruct(l).x = c(1,idxlabel+(1:n));
cstruct(l).y = c(2,idxlabel+(1:n));
cstruct(l).level = c(1,idxlabel);
l = l+1;
idxlabel = idxlabel+n+1;
end

end % contour2poly

% Bruno
From: Walter Roberson on
Sujit wrote:
> How can I quickly convert contours to polygons? i.e. How can I quickly
> extract all polygons (x and y) from C, where [C,g] = contour(Z); ?
>
> The structure of C looks complicated -- anyone have something handy?

Take the other approach -- go into the handle that is returned!

polycells = arrayfun( @(ch) horzcat( get(ch,'XData'), get(ch,'YData')),
get(g,'Children'),'Uniform',0); %g is the handle from contour()

will return a cell array, each of which contains an array of coordinate pairs,
X in column 1 and Y in column 2. If that's not exactly how you you would like
the output, you can adjust to suit your needs. Note that the fetched XData and
YData will be column vectors.
From: Walter Roberson on
Bruno Luong wrote:
> "Sujit " <kirpekar(a)gmail.com> wrote in message
> <hodo49$t4u$1(a)fred.mathworks.com>...
>> How can I quickly convert contours to polygons?

> function cstruct = contour2poly(c)

> while idxlabel <= size(c,2)


Ah, but can you code it without an explicit loop? ;-)

(I have a mental outline for a recursive approach, and a hack in mind that
would use arrayfun...)
From: Bruno Luong on
Walter Roberson <roberson(a)hushmail.com> wrote in message
> Ah, but can you code it without an explicit loop? ;-)
>
> (I have a mental outline for a recursive approach, and a hack in mind that
> would use arrayfun...)

Of course you are right Walter, it is straightforward to convert while-loop to equivalent recursive call:

function cstruct = contour2poly(c)

if isempty(c)
cstruct = struct('level', {}, 'x', {}, 'y', {});
else
n = c(2,1);
idx = 2:n+1;
cstruct = [struct('level', c(1,1), 'x', c(1,idx), 'y', c(2,idx)) ...
contour2poly(c(:,n+2:end))];
end

end % contour2poly

% Bruno
 |  Next  |  Last
Pages: 1 2
Prev: legend title
Next: MATLAB CODE to DSK C6713