如何将在scikit图像find_contours中创建的轮廓导出到shapefile或geojson?

我正在尝试在卫星图像上运行后将scikit-image.measure.find_contours()函数的结果导出为shapefile或geojson.

输出是像(行,列)这样的数组,其轮廓沿坐标,其中有很多.

如何绘制各种轮廓的坐标,并将其导出到shapefile(可以设置适当的投影等)?

我当前的代码,其中“ mask”是我处理过的图像:

from skimage import measure
import matplotlib.pyplot as plt

contours = measure.find_contours(mask, 0.5)

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

解决方法:

由rasterio和fiona的主要开发人员改编为post的以下内容应该可以正常工作,尽管我敢肯定您需要进行更多调整.它使用rasterio.features.shapes来识别图像中具有一定值的连续区域,并根据栅格的变换返回相关联的坐标.然后使用fiona将这些记录写入shapefile.

import fiona
import rasterio.features

schema = {"geometry": "Polygon", "properties": {"value": "int"}}

with rasterio.open(raster_filename) as raster:
    image = raster.read()
    # use your function to generate mask
    mask = your_thresholding_function(image)
    # and convert to uint8 for rasterio.features.shapes
    mask = mask.astype('uint8')
    shapes = rasterio.features.shapes(mask, transform=raster.transform)
    # select the records from shapes where the value is 1,
    # or where the mask was True
    records = [{"geometry": geometry, "properties": {"value": value}}
               for (geometry, value) in shapes if value == 1]
    with fiona.open(shape_filename, "w", "ESRI Shapefile",
                    crs=raster.crs.data, schema=schema) as out_file:
        out_file.writerecords(records)
上一篇:python-Matplotlib:如何从轴上删除一个轮廓元素与其他绘制的元素?


下一篇:Python---列表(基本操作、内置函数、切片等)(细讲)