How can I export a matlab contour as a polygon shapefile?

45 visualizaciones (últimos 30 días)
Anna Weeks
Anna Weeks el 26 de Sept. de 2017
Editada: Aleksey Tipikin el 4 de Feb. de 2025 a las 19:22
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.

Respuestas (1)

Walter Roberson
Walter Roberson el 26 de Sept. de 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 comentarios
Walter Roberson
Walter Roberson el 26 de Sept. de 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
Aleksey Tipikin el 4 de Feb. de 2025 a las 19:12
Editada: Aleksey Tipikin el 4 de Feb. de 2025 a las 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)

Iniciar sesión para comentar.

Categorías

Más información sobre Surface and Mesh Plots en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by