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

조회 수: 48 (최근 30일)
Anna Weeks
Anna Weeks 2017년 9월 26일
편집: Aleksey Tipikin 2025년 2월 4일 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.

답변 (1개)

Walter Roberson
Walter Roberson 2017년 9월 26일
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
Walter Roberson
Walter Roberson 2017년 9월 26일
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 2025년 2월 4일 19:12
편집: Aleksey Tipikin 2025년 2월 4일 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)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by