栅格数据转换成矢量数据python代码
在GIS相关的数据处理过程中,经常会遇到将栅格数据转换成矢量数据的需求。本文将介绍使用Python代码实现栅格到矢量的转换过程,实现从tiff格式的高程栅格数据转换成shp格式的矢量数据。
1.导入相关的Python库
本次转换所需的库包括GDAL、OSR、ogr、numpy、math,需要在Python环境中安装。
```
from osgeo import gdal,ogr,osr
import numpy as np
import math
```
2.定义需要转换的栅格数据路径
```
src_path = 'test_dem.tiff'
```
3.获取栅格数据的基本信息
GDAL库提供了获取栅格数据基本信息的方法,通过下面的代码可得到栅格数据的行数、列数和波段数,以及地理坐标系和投影信息。
```
def GetGeoInfo(filename):
python代码转换 dataset = gdal.Open(filename)
cols = dataset.RasterXSize
rows = dataset.RasterYSize
bands = dataset.RasterCount
geotransform = dataset.GetGeoTransform()
projection = dataset.GetProjection()
return cols, rows, bands, geotransform, projection
cols, rows, bands, geotransform, projection = GetGeoInfo(src_path)
```
4.将栅格数据读入数组中
使用GDAL库将栅格数据读入numpy数组中,这样可以方便对它进行进一步的处理。
```
def read_tiff(filename):
dataset=gdal.Open(filename)
if dataset is None:
print('Could not open ' + filename)
it(1)
cols = dataset.RasterXSize
rows = dataset.RasterYSize
bands = dataset.RasterCount
data = dataset.ReadAsArray(0, 0, cols, rows)
return data
data = read_tiff(src_path)
```
5.从栅格数组中提取矢量要素
将栅格数组中的高程值进行阈值分割,得到一个布尔类型的数组。然后通过对这个数组进行腐蚀和膨胀操作,得到目标要素的外形轮廓。同时设置目标要素的地理坐标系以及属性信息。
```
def raster2vector(data,geotransform,projection):
shape = np.shape(data)
dst_layername = "test_polygon"
mem_driver = ogr.GetDriverByName("memory")
mem_ds = mem_driver.CreateDataSource('out')
srs = osr.SpatialReference()
srs.ImportFromWkt(projection)
dst_layer = mem_ds.CreateLayer(dst_layername, srs)
fd = ogr.FieldDefn('Value', ogr.OFTInteger)
dst_layer.CreateField(fd)
# get threshold and create binary numpy array
threshold = 10
binary_array = np.zeros(shape, dtype=bool)
binary_array[data >= threshold] = True
se = np.ones((3,3), dtype=bool)
eroded = np.zeros(shape, dtype=bool)
dilated = np.zeros(shape, dtype=bool)
for j in range(shape[0]):
eroded[j,:] = np.logical_not(np.logical_xor(binary_array[j,:], se[0,1]))
dilated[j,:] = np.logical_not(np.logical_xor(binary_array[j,:], se[1,1]))
for i in range(shape[1]):
eroded[:,i] = np.logical_and(eroded[:,i], np.logical_not(np.logical_xor(binary_array[:,i], se[1,0])))
dilated[:,i] = np.logical_and(dilated[:,i], np.logical_not(np.logical_xor(binary_array[:,i], se[1,1])))
contours = dilated.astype(np.uint8) - eroded.astype(np.uint8)
contours_poly = []
for contour in contours:
contour_poly = []
points = np.o(contour))
hull_index = vexHull(points, returnPoints=False)
hull_points = points[hull_index.squeeze()]
contour_poly.append(hull_points)
contours_poly.append(contour_poly)
for contour in contours_poly:
multipoly = ogr.Geometry(ogr.wkbMultiPolygon)
ring = ogr.Geometry(ogr.wkbLinearRing)
for point in contour[0]:
px = geotransform[0] + point[1] * geotransform[1] + point[0] * geotransform[2]
py = geotransform[3] + point[1] * geotransform[4] + point[0] * geotransform[5]
ring.AddPoint(px,py)
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
multipoly.AddGeometry(poly)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论