python gdal 读取影像通过无效值,识别影像有效边界并生成shapefile文件
时间: 2024-04-07 14:30:09 浏览: 271
Gdal读取与生成图像
要通过无效值识别影像的有效边界并生成shapefile文件,你可以使用GDAL库和OGR库。以下是一个示例代码:
```python
from osgeo import gdal, ogr
import numpy as np
# 打开影像文件
dataset = gdal.Open('path_to_your_image.tif')
# 获取第一个波段
band = dataset.GetRasterBand(1)
# 读取影像数据为NumPy数组
data = band.ReadAsArray()
# 获取无效值
no_data_value = band.GetNoDataValue()
# 创建掩码数组
mask = np.not_equal(data, no_data_value)
# 获取有效边界
rows = np.any(mask, axis=1)
cols = np.any(mask, axis=0)
min_row, max_row = np.where(rows)[0][[0, -1]]
min_col, max_col = np.where(cols)[0][[0, -1]]
# 计算有效边界的地理坐标
transform = dataset.GetGeoTransform()
ulx = transform[0] + min_col * transform[1] + min_row * transform[2]
uly = transform[3] + min_col * transform[4] + min_row * transform[5]
lrx = transform[0] + (max_col + 1) * transform[1] + (max_row + 1) * transform[2]
lry = transform[3] + (max_col + 1) * transform[4] + (max_row + 1) * transform[5]
# 创建shapefile文件
driver = ogr.GetDriverByName('ESRI Shapefile')
shapefile_path = 'path_to_output_shapefile.shp'
shapefile = driver.CreateDataSource(shapefile_path)
***
阅读全文