python代码,将shapfile文件转换为polygon格式,并用该文件裁剪遥感影像。
时间: 2024-11-27 20:17:43 浏览: 52
在Python中,我们可以使用`geopandas`库来处理Shapefile文件,并结合`rasterio`或`geopandas`对遥感影像进行裁剪。这里是一个简单的步骤:
首先,安装必要的库:
```bash
pip install geopandas rasterio Fiona
```
然后,你可以按照以下步骤进行操作:
1. 导入库并读取Shapefile:
```python
import geopandas as gpd
# 替换path_with_your_shapefile为你Shapefile的实际路径
shape_df = gpd.read_file('path_with_your_shapefile.shp')
```
2. 确保地理参考信息一致,如果需要,可以使用`to_crs()`方法将数据转换到与遥感影像相同的坐标系统:
```python
if not shape_df.crs.equals(raster_image.crs):
shape_df = shape_df.to_crs(raster_image.crs)
```
3. 使用`clip()`函数裁剪遥感影像(假设`raster_image`是一个`rasterio.io.DatasetReader`对象):
```python
from rasterio.warp import transform_bounds
# 获取形状区经纬度范围
bounds = shape_df.total_bounds
x_min, y_max, x_max, y_min = bounds
# 转换裁剪区域到影像的坐标系
src_transform, src_crs = raster_image.transform, raster_image.crs
crop_window = transform_bounds(src_crs, target_crs, x_min, y_max, x_max, y_min, densify_pts=10)
# 实际裁剪
cropped_raster = raster_image.read(window=crop_window)
```
4. 最后保存裁剪后的影像:
```python
# 如果你想保存为新的tif文件,可以使用rasterio.open()创建一个新的文件
with rasterio.open('output_clipped.tif', 'w', **raster_image.meta, driver='GTiff') as dst:
dst.write(cropped_raster)
```
阅读全文
相关推荐


















