How to fill contours in a contour matrix
Show older comments
Yeah, I know, I could use contourf, but I want to draw the contours generated by contourc on another plot. What I need help with is how to close the contours, in particular those at the edge of the data.
If you run this code, you will see what I mean. How to properly close the contour at the lower left corner and the one at the top.
data = [ ...
9 9 9 9 1 1 1 1 1 1 1 1 1 1 1 1; ...
9 9 9 9 1 1 1 1 1 1 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 9 9 9 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 9 9 9 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 1 9 1 1 1 1 1 1 1; ...
1 1 1 1 1 1 1 9 9 9 1 1 1 1 1 1; ...
1 1 1 1 1 1 9 9 9 9 9 1 1 1 1 1];
figure(1)
clf
subplot(2,2,1)
imagesc(data)
set(gca, 'YDir', 'normal', 'XLim', [1 12], 'YLim', [1 12]);
subplot(2,2,2)
C = contourf(data, 1);
subplot(2,2,3)
kdx = 1;
while (1)
l = C(1,kdx);
n = C(2,kdx);
x = C(1,(kdx+1):(kdx+n-1));
y = C(2,(kdx+1):(kdx+n-1));
plot(x, y); hold on
patch(x, y, l);
kdx = kdx + n + 1;
if (kdx > size(C,2))
break;
end
end
set(gca, 'XLim', [1 12], 'YLim', [1 12]);

Thanks so much Bill
3 Comments
Image Analyst
on 9 Sep 2014
What really do you want to do? It's not clear what your ultimate goal is. I'm wondering why you're dealing with contour and patch rather than just the image directly. I don't want you to just say "I want to close the contours" -- I want to know why you think you need to do that and maybe we can come up with a better approach. If you get the desired output image (of which, I'm not clear what that might be), then what would you do with it?
Otis
on 9 Sep 2014
Otis
on 11 Sep 2014
Answers (1)
Image Analyst
on 9 Sep 2014
0 votes
I'd do it as an image. See http://blogs.mathworks.com/steve/2009/02/18/image-overlay-using-transparency/ If you only have one level for the contour, as your one example shows (just the "red" level) then you can threshold and get a binary image and overlay the binary image as Steve shows in his blog. If you want outlines, you can use bwboundaries() in the Image Processing Toolbox and then use plot() to plot the boundaries as graphical lines in the overlay above the image.
Categories
Find more on Lighting, Transparency, and Shading in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!