我想使用分水岭作为界限来裁剪栅格数据。我已经使用 Fiona 和 Rasterio 进行了尝试。
这是我的代码:
import fiona
import rasterio
from rasterio.rio.clip import clip
with fiona.open("oreto_bacino2.shp", "r") as shapefile:
geoms = [feature["geometry"] for feature in shapefile]
with rasterio.open("cn.asc") as src:
out_image, out_transform = clip (geoms, src, 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("cn_masked.tif", "w", **out_meta) as dest:
dest.write(out_image)
这是我得到的错误:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
抛出这个错误:
AttributeError: 'rasterio._io.RasterReader' object has no attribute 'replace'
有人知道我的手术的正确方法吗?
请您参考如下方法:
像 rasterio.rio.clip.clip 这样的 rio 函数不能作为 Python 函数调用,因为它们已经附加了一个命令行界面(所有那些装饰器),并针对从那里获取参数进行了优化。
你可以改为 look into the code of the clip function看看它是如何实现剪辑和模仿的。它基本上从几何边界创建一个窗口,并使用该窗口从源栅格中读取(窗口化读取)。
或者您可以关注example from the docs它使用 rasterio.mask.mask(..., crop=True) 并且不仅会剪裁到边界,还会遮盖几何体外部的像素,这可能更接近您想要的效果。
