Received AttributeError: 'str' object has no attribute 'get' when use raster_geometry_mask

Received AttributeError: 'str' object has no attribute 'get' when use raster_geometry_mask

我需要通过 rasterio 和 geopandas 从 .tif 和 .shp 文件创建蒙版(二进制图像)。以下是我的代码:

import numpy as np
import pandas as pd
import os
import rasterio
import rasterio.features
import rasterio.warp
from rasterio.plot import show
from rasterio.mask import mask
import shapely
from fiona.crs import from_epsg
import geopandas as gpd

dataset = rasterio.open('/content/drive/My Drive/Data4Colab/Baitap2/img.tif')
polygons = gpd.read_file('/content/drive/My Drive/Data4Colab/Baitap2/shp/paddy_bg.shp')

shapes = []
geo = polygons.values[:, 1]
for i in range(len(polygons)):
    shapes.append(geo[i])

out = rasterio.mask.raster_geometry_mask(dataset, shapes, crop=True)

这是我的形状(列表):

['background',
 'background',
 'background',
 'background',
 'background',
 'background',
 'paddy',
 'paddy',
 'paddy',
 'paddy',
 'paddy',
 'paddy']

我收到一个错误:AttributeError: 'str' object has no attribute 'get'.

这是类型不匹配问题。 rasterio.mask.raster_geometry_mask expects shapes to be "a GeoJSON-like dict or an object that implements the Python geo interface protocol (such as a Shapely Polygon)",但您从 Geopandas 中读取的内容可能不符合该要求。

一种方法是使用 fiona 模块读取 shapefile:

import fiona
import rasterio

dataset = rasterio.open('/path/to/your/img.tif')

with fiona.open("tests/data/box.shp", "r") as shapefile:
    shapes = [feature["geometry"] for feature in shapefile]

out = rasterio.mask.raster_geometry_mask(dataset, shapes, crop=True)

如果您在创建掩码后仍需要使用 Geopandas,您可以之后再次将它们与 Pandas DataFrame 相关联(通过使用简单的索引顺序或 ID 属性形状等)。