How can I export a matlab contour as a polygon shapefile?
23 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.
8 Comments
Cedric
on 26 Sep 2017
Edited: Cedric
on 26 Sep 2017
Ok, now here is why this cannot work directly. If you create polygons using contours, you don't create holes (interior boundaries), which means that polygons are not disjoint. We can see this importing a contour simpler than the cameraman:
[X,Y,Z] = peaks;
figure
cmatrix = contour( X*60, Y*30, Z, 5 ) ;
shapedata = contour2shape(cmatrix) ;
shapewrite(shapedata, 'peaks_polygons.shp') ;
Now if we import that in a GIS, and use Z for defining polygons color, we get:
which seems fine, but if we set no color for the top polygon, we see that it is not:
The polygon below the dark one has no hole. This can not work for a series of geoprocessing operations (zonal stat, intersects, etc). There are ways to clean it though, nothing automatic as far as I remember unless you want to involve a little bit of Python (but look it up, don't take my work for that because I am programming most of my GIS processing and I am not a good user of the ArcGIS interface .. if it is what you are using).
Then if you keep exporting polylines ('PolyLine' in the call to SHAPEWRITE), you can convert polylines to polygons (in ArcGIS this is under "Data Management Tools/Features/Feature to Polygon") and you get the following, where I removed the filling of the top polygon:
This works, there is no overlay, but we loose Z or the attributes in the process.
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 ?
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!