Contours around scipy labeled regions in a 2D grid

…衆ロ難τιáo~ 提交于 2020-01-22 16:11:20

问题


I'm trying to find the bounding polygons of all of the wholes in a 2D grid with a large no-data value (1e6). I've got the listing of holes working using scipy's label. Without dipping into gdal's polygonalize, is there an easy way to generate the bounding polygons? I see that there is matplotlib.pylab.contour, but this tries to draw a plot, which I really don't want. Any recommendation on how to get bounding polygons for each label (preferably with a way to simplify the polygons a little if possible)? I'm sure I can write something that will walk the bounds of each labelled hole, but is there something that already exists?

from osgeo import gdal
from scipy import ndimage

dem_file = gdal.Open('dem.tif')
dem = dem.file.GetRasterBand(1).ReadAsArray()

# Get a binary image of the no-data regions.  The no-data value is large
bin = dem > 9e5

# Find all the wholes.  Anything with a label > 0.
labels, num_labels = ndimage.measurements.label(bin)
num_labels
1063

# The hole's label and size. Skip 0 as that label has all the valid data.
holes = [(label, sum(labels==label)) for label in range(1, num_labels)]
holes[:3]
[(1, 7520492),
 (2, 1),
 (3, 1),]

e.g. rather than countouring, I'm looking for the bounds of all of these white regions as viewed in qgis, which was done with gdal_polygonalize.py.


回答1:


Thanks to Joe Kington for pointing me to Scikit Image.

from skimage import measure
contours = measure.find_contours(labels, 1)

contours[-1]
array([[ 2686.99905927,  1054.        ],
       [ 2686.        ,  1053.00094073],
       [ 2685.00094073,  1054.        ],
       [ 2686.        ,  1054.99905927],
       [ 2686.99905927,  1054.        ]])

imshow(labels)
for n, contour in enumerate(contours):
    plt.plot(contour[:,1], contour[:, 0], linewidth=2)

After zooming in the bottom left corner:



来源:https://stackoverflow.com/questions/14572933/contours-around-scipy-labeled-regions-in-a-2d-grid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!