【问题标题】:Converting Vector (.shp) to Raster (.tiff) using Python GDAL library使用 Python GDAL 库将矢量 (.shp) 转换为光栅 (.tiff)
【发布时间】: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. 多边形和线形状文件的输出中的正确形状。

【问题讨论】:

    标签: python gis gdal


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 2021-05-01
      • 1970-01-01
      • 2012-10-05
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多