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

Cat*_*ate 5 python arrays shapefile contour scikit-image

我正在尝试在卫星图像上运行后将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)
Run Code Online (Sandbox Code Playgroud)

jdm*_*cbr 7

以下内容改编自and的主要开发人员的帖子,应该可以工作,但我相信您需要再适应一些。它用于识别图像中具有某些值的连续区域,并根据栅格的变换返回关联的坐标。然后使用 将这些记录写入 shapefile 。rasteriofionarasterio.features.shapesfiona

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)
Run Code Online (Sandbox Code Playgroud)