使用Shapefile裁剪Raster时触发TypeError错误求助
解决Rasterio裁剪时的TypeError: can't multiply sequence by non-int of type 'Affine'错误
问题重现
尝试用与栅格文件坐标系一致的Shapefile裁剪栅格,执行到rasterio.mask.mask时触发错误:TypeError: can't multiply sequence by non-int of type 'Affine',原代码如下:
# Read Shapefile with fiona.open("/content/drive/My Drive/shapefile/shape_files/lidar_shape.shp", "r") as shapefile: shapes = [feature["geometry"] for feature in shapefile] # read imagery file with rasterio.open("/content/drive/My Drive/shapefile/imagery_trans.tif") as src: out_image,out_transform = rasterio.mask.mask(src, shapes, crop=True) out_meta = src.meta # Save clipped imagery out_meta.update({"driver": "GTiff", "height": out_image.shape[1], "width": out_image.shape[2], "transform": out_transform}) with rasterio.open("/content/drive/My Drive/shapefile/imagery_trans_clip.tif", "w", **out_meta) as dest: dest.write(out_image)
错误原因
这个错误的核心是传入rasterio.mask.mask的几何对象格式不符合要求:原代码读取的是Shapefile中原始的GeoJSON格式字典,而非Rasterio所需的shapely几何对象,导致在与Affine变换矩阵进行空间运算时类型不匹配。即使坐标系一致,格式错误也会触发该异常。
解决方法
修改代码,将GeoJSON几何转换为shapely对象,并添加坐标系验证步骤,确保两者完全匹配:
修改后的代码
import fiona import rasterio from rasterio.mask import mask from shapely.geometry import shape from rasterio.crs import CRS # 读取Shapefile并转换几何为shapely对象 with fiona.open("/content/drive/My Drive/shapefile/shape_files/lidar_shape.shp", "r") as shapefile: shape_crs = CRS.from_wkt(shapefile.crs_wkt) # 过滤空几何,转换为shapely对象 shapes = [shape(feature["geometry"]) for feature in shapefile if feature["geometry"] is not None] # 读取栅格文件 with rasterio.open("/content/drive/My Drive/shapefile/imagery_trans.tif") as src: # 强制验证坐标系一致性 assert src.crs == shape_crs, "栅格与Shapefile坐标系不匹配,请先对齐坐标系" out_image, out_transform = mask(src, shapes, crop=True) out_meta = src.meta.copy() # 更新元数据并保存裁剪后的栅格 out_meta.update({ "driver": "GTiff", "height": out_image.shape[1], "width": out_image.shape[2], "transform": out_transform }) with rasterio.open("/content/drive/My Drive/shapefile/imagery_trans_clip.tif", "w", **out_meta) as dest: dest.write(out_image)
关键修改点
- 导入
shapely.geometry.shape,将原始GeoJSON几何字典转换为shapely几何对象,这是Rasterio mask函数的标准输入类型 - 添加坐标系验证,用
assert明确确认栅格与Shapefile的坐标系一致,避免隐性的不匹配问题 - 过滤Shapefile中的空几何,防止无效数据干扰运算
- 使用
src.meta.copy()复制元数据,避免修改原始栅格的元数据
内容的提问来源于stack exchange,提问作者PRAJAKTA
相关产品推荐
相关产品推荐

