【发布时间】:2020-01-20 10:41:52
【问题描述】:
我正在尝试将矢量 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. 多边形和线形状文件的输出中的正确形状。
【问题讨论】: