rasterio 按经纬度裁剪栅格
时间: 2023-10-18 09:10:59 浏览: 40
要按经纬度裁剪栅格,可以使用 `rasterio.mask.mask` 函数。以下是一个示例代码:
```python
import rasterio
from rasterio.mask import mask
from shapely.geometry import box
# 定义裁剪范围的经纬度坐标
lon_min, lat_min, lon_max, lat_max = [100, 20, 110, 30]
# 创建裁剪范围的 Shapely 几何对象
bbox = box(lon_min, lat_min, lon_max, lat_max)
# 打开栅格文件
with rasterio.open("path/to/raster.tif") as src:
# 裁剪栅格
out_image, out_transform = mask(src, [bbox], crop=True)
out_meta = src.meta.copy()
# 更新元数据
out_meta.update({
"height": out_image.shape[1],
"width": out_image.shape[2],
"transform": out_transform
})
# 保存裁剪后的栅格文件
with rasterio.open("path/to/output.tif", "w", **out_meta) as dest:
dest.write(out_image)
```
在这个示例中,我们首先定义了裁剪范围的经纬度坐标,然后创建了一个 Shapely 几何对象。接下来,我们使用 `rasterio.mask.mask` 函数对栅格进行裁剪,并且更新了元数据。最后,我们保存裁剪后的栅格文件。