python - 使用 Python GDAL 库将矢量 (.shp) 转换为光栅 (.tiff)
问题描述
我正在尝试将矢量 shapefile 转换为光栅 tiff 文件。我改编了 Michael Diener 的 Python Geospatial Analysis Cookbook 的源代码。该代码适用于线和多边形 shapefile,但仅显示点 shapefile 的黑屏。
def main(shapefile):
#making the shapefile as an object.
input_shp = ogr.Open(shapefile)
#getting layer information of shapefile.
shp_layer = input_shp.GetLayer()
#pixel_size determines the size of the new raster.
#pixel_size is proportional to size of shapefile.
pixel_size = 0.1
#get extent values to set size of output raster.
x_min, x_max, y_min, y_max = shp_layer.GetExtent()
#calculate size/resolution of the raster.
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
#get GeoTiff driver by
image_type = 'GTiff'
driver = gdal.GetDriverByName(image_type)
#passing the filename, x and y direction resolution, no. of bands, new raster.
new_raster = driver.Create(output_raster, x_res, y_res, 1, gdal.GDT_Byte)
#transforms between pixel raster space to projection coordinate space.
new_raster.SetGeoTransform((x_min, pixel_size, 0, y_min, 0, pixel_size))
#get required raster band.
band = new_raster.GetRasterBand(1)
#assign no data value to empty cells.
no_data_value = -9999
band.SetNoDataValue(no_data_value)
band.FlushCache()
#main conversion method
gdal.RasterizeLayer(new_raster, [1], shp_layer, burn_values=[255])
#adding a spatial reference
new_rasterSRS = osr.SpatialReference()
new_rasterSRS.ImportFromEPSG(2975)
new_raster.SetProjection(new_rasterSRS.ExportToWkt())
return gdal.Open(output_raster)
所以,我的问题是:
我要在代码中进行哪些更改以使其也适用于点 shapefile?以及如何让我的最终输出光栅文件与输入矢量文件具有相同的颜色?
在代码中起作用的事情是: 1. 正确获取输入并返回输出。2. 获得适当的尺寸/分辨率并创建所需分辨率的栅格。3. 多边形和线形状文件的输出中的正确形状。
解决方案
如果要保留现有代码,可以添加ALL_TOUCHED
选项并将其设置为TRUE
.
将光栅化线更改为:
gdal.RasterizeLayer(new_raster, [1], shp_layer,
burn_values=[255],
options=['ALL_TOUCHED=FALSE'])
但是,您也可以考虑使用与命令行实用程序的绑定,因为这样可以节省大量代码。例如:
input_shp = ogr.Open(shape_file)
shp_layer = input_shp.GetLayer()
pixel_size = 0.1
xmin, xmax, ymin, ymax = shp_layer.GetExtent()
ds = gdal.Rasterize(output_raster, shape_file, xRes=pixel_size, yRes=pixel_size,
burnValues=255, outputBounds=[xmin, ymin, xmax, ymax],
outputType=gdal.GDT_Byte)
ds = None
推荐阅读
- python - 在python中出现错误,打印模式
- flutter - 如何创建扩展方法来着色、加粗、删除字符串上的内容
- fortran - Fortran 中的稀疏数组
- javascript - 单击按钮时,我想使用 Javascript 将文本字段的值增加一
- xml - 使用 XSLT 2.0 替换 XML 中的部分属性
- mysql - 如何在 Spring Boot 应用程序中从数据库表中填充实体
- html - h1 与导航栏不对齐
- python - Django,使用和不使用参数调用相同的视图函数
- javascript - 是否可以在不显示在页面/画布上的情况下获得图形的基数 64(Graph.Js)
- git - 如何说服 Xcode 11.5 在 Project Navigator 中显示我的 README.md?