用python写一个遥感影像批量栅格矢量化代码
时间: 2023-12-17 09:23:14 浏览: 143
python gdal + skimage实现基于遥感影像的传统图像分割及合并外加矢量化
以下是一个基于GDAL库的python代码,用于批量将遥感影像栅格化为矢量文件:
```python
import os
import glob
import gdal
from osgeo import ogr
path = 'path/to/raster/files'
output_path = 'path/to/vector/files'
def raster_to_vector(raster_file, vector_file):
# Open raster file and get metadata
ds = gdal.Open(raster_file)
band = ds.GetRasterBand(1)
geotransform = ds.GetGeoTransform()
proj = ds.GetProjection()
cols = ds.RasterXSize
rows = ds.RasterYSize
# Create output shapefile and layer
driver = ogr.GetDriverByName('ESRI Shapefile')
out_ds = driver.CreateDataSource(vector_file)
out_layer = out_ds.CreateLayer(vector_file, srs=ogr.osr.SpatialReference(proj), geom_type=ogr.wkbPolygon)
# Create field for pixel value
field_def = ogr.FieldDefn('Value', ogr.OFTInteger)
out_layer.CreateField(field_def)
# Create polygons from raster cells
for y in range(rows):
for x in range(cols):
# Get pixel value and check if it is nodata
value = band.ReadAsArray(x, y, 1, 1)[0, 0]
if value == band.GetNoDataValue():
continue
# Calculate polygon vertices
ulx, xres, xskew, uly, yskew, yres = geotransform
xcoord = ulx + (x + 0.5) * xres
ycoord = uly + (y + 0.5) * yres
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(xcoord - 0.5 * xres, ycoord - 0.5 * yres)
ring.AddPoint(xcoord + 0.5 * xres, ycoord - 0.5 * yres)
ring.AddPoint(xcoord + 0.5 * xres, ycoord + 0.5 * yres)
ring.AddPoint(xcoord - 0.5 * xres, ycoord + 0.5 * yres)
ring.AddPoint(xcoord - 0.5 * xres, ycoord - 0.5 * yres)
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
# Create feature and add to layer
feature = ogr.Feature(out_layer.GetLayerDefn())
feature.SetGeometry(poly)
feature.SetField('Value', value)
out_layer.CreateFeature(feature)
# Clean up
ds = None
out_ds = None
# Loop through raster files
for raster_file in glob.glob(os.path.join(path, '*.tif')):
# Create output vector file name
vector_file = os.path.join(output_path, os.path.splitext(os.path.basename(raster_file))[0] + '.shp')
# Convert raster to vector
raster_to_vector(raster_file, vector_file)
```
这个代码将遥感影像文件夹中的所有.tif文件转换为矢量文件,输出到指定的路径下。可以根据需要对输出的矢量文件进行进一步处理,如合并、剪裁等操作。
阅读全文