Gdal_rasterize nodata_value 无效

Gdal_rasterize nodata_value does not work

我想栅格化由多边形构成的源图层。无论我给 "NoData_value" 赋什么值,数组中的结果总是 = 0。 我正在使用 python 3.4。 谁能帮我理解一下?

source_srs = source_layer.GetSpatialRef()
x_min, x_max, y_min, y_max = source_layer.GetExtent()

# parameters of output file
xSize = math.ceil((x_max - x_min) / pixel_size)  # number of pixels in the x direction given pixel_size, rounded up to the nearest pixel
ySize = math.ceil((y_max - y_min) / pixel_size)  # number of pixels in the y direction given pixel_size, rounded up to the nearest pixel
x_res = int((x_max - x_min) / xSize)  # size of pixel in meters rounded to fit bbox
y_res = int((y_max - y_min) / ySize)  # size of pixel in meters rounded to fit bbox

NoData_value = -9999

# Create output dataset as memory
target_ds = gdal.GetDriverByName('MEM').Create('', xSize, ySize, gdal.GDT_Byte)
target_ds.SetGeoTransform((x_min, x_res, 0, y_max, 0, -y_res))
wkt_projection = source_srs.ExportToWkt()
target_ds.SetProjection(wkt_projection)

band = target_ds.GetRasterBand(1)
band.SetNoDataValue(NoData_value)

# rasterize
gdal.RasterizeLayer(target_ds, [1], source_layer, options=["ATTRIBUTE=expo" ])

# Read as numpy array
array = band.ReadAsArray()

是否希望多边形外的值具有 NoData_value

然后,添加

band.Fill(NoData_value)

在调用 gdal.RasterizeLayer 之前。您需要这个,因为 gdal.RasterizeLayer 仅修改(刻录)多边形内的值。

您需要将格式 gdal.GDT_Byte 更改为可以处理 -9999 的格式,例如 GDT_Float32:

target_ds = gdal.GetDriverByName('MEM').Create('', int(xSize), int(ySize), 1, gdal.GDT_Float32)

注意:数据类型是第 5 个参数,而不是代码中的第 4 个。第 4 个参数应用于波段数: http://www.gdal.org/classGDALDriver.html#adb7bff9007fa5190d6cf742cf76942a8

我测试过,适合我的尺码。