使用Python GDAL库将矢量(.shp)转换为栅格(.tiff)

4

我正在尝试将矢量shapefile转换为栅格tiff文件。我参考了Michael Diener的Python地理空间分析食谱中的源代码。该代码适用于线和多边形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. 对于多边形和线状shapefile,在输出中呈现正确的形状。

1个回答

4

如果想保留您现有的代码,可以添加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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接