How can I export a matlab contour as a polygon shapefile?
45 views (last 30 days)
Show older comments
I have a rainfall map for which I have created contour lines using the 'contour' function. I need to export the output contours as a shapefile.
0 Comments
Answers (1)
Walter Roberson
on 26 Sep 2017
This turned out to be easy.
First, the driver function:
function c2s_driver
YourData = imread('cameraman.tif');
cmatrix = contour(YourData);
shapedata = contour2shape(cmatrix);
shapewrite(shapedata, 'camera_contours.shp');
end
and the workhorse:
function shp = contour2shape(cmatrix)
%Converts a contour matrix to a shape structure
%needs https://www.mathworks.com/matlabcentral/fileexchange/43162-c2xyz-contour-matrix-to-coordinates
[x, y, z] = C2xyz(cmatrix);
shp = struct('Geometry', 'PolyLine', 'X', x, 'Y', y, 'Z', num2cell(z));
end
Notice this needs C2xyz which you can download from the File Exchange or install using Add-On Explorer.
9 Comments
Walter Roberson
on 26 Sep 2017
Thanks, I fixed the typo.
I did not try to code insides with clockwise / counter-clockwise pairs. It might be a bit involved to figure out which polygon borders which.
I wonder if it would make more sense to use the z as a "measure" PolygonM type rather than an attribute? Or perhaps make it 3D points with constant Z ?
Aleksey Tipikin
on 4 Feb 2025 at 19:12
Edited: Aleksey Tipikin
on 4 Feb 2025 at 19:22
What about polygons in the corner? They don't closes correctly after extraction. Here is the example.
%Latitude and longitude vectors
lat = -70:70;
lon = -180:180;
%full grid coordinates
[lat1,lon1] = ndgrid(lat,lon);
Z = sind(lat1*2)+sind(lon1*2);
%Georeference object
R=georefpostings([lat(1),lat(end)],[lon(1),lon(end)],size(lat1));
%Visualize maps
figure;
Map1 = worldmap('World');
setm(Map1,'FontSize',8,'MapProjection','mercator','MapLatLimit',[-70 70])
tightmap;
%Show Z
%contourfm(lat1,lon1,Z,25,'LineStyle','none');
contourfm(Z,R,25,'LineStyle','none');
contourcbar;
%Show coastline
geoshow('landareas.shp','FaceColor','none');
%Show specified level
[C,h] = contourfm(Z,R,[0.5 0.5]);
h.Children(3).FaceAlpha = 0;
h.Children(2).FaceAlpha = 0.4;
h.Children(2).FaceColor = 'w';
%Make polygon with coordinates of contour at specified level
[x, y, ~] = C2xyz(C);
g2 = geoshape(y{1},x{1},'Geometry','polygon');
geoshow(g2,'EdgeColor','k','FaceColor','r','FaceAlpha',0.4)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1825177/image.jpeg)
See Also
Categories
Find more on Surface and Mesh Plots 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!