Share
Go down
avatar
Admin
Posts : 155
Join date : 2017-11-11
Age : 27
View user profilehttp://net-media.yoo7.com

how solving Problem Gdal_rasterize nodata_value does not work ’

on Thu Dec 14, 2017 10:54 am
I want to rasterize a source layer made of polygons. No matter what value I assign to "NoData_value", the outcome in my array is always = 0. I am using python 3.4. Can anyone help me understand please ?
Code:
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()

Answer
Do you want the values outside the polygons to have NoData_value?

Then, add
Code:
band.Fill(NoData_value)
before calling gdal.RasterizeLayer. You need this because gdal.RasterizeLayer only modifies (burn) the values inside the polygons.

You will need to change the format gdal.GDT_Byte to a format that can handle -9999 such as for example GDT_Float32:
Code:
target_ds = gdal.GetDriverByName('MEM').Create('', int(xSize), int(ySize), 1, gdal.GDT_Float32)
Note : data type is the 5th argument, not the 4th as in your code. The 4th argument should be used for the number of bands: http://www.gdal.org/classGDALDriver.html#adb7bff9007fa5190d6cf742cf76942a8

I tested and it works on my size.
Back to top
Permissions in this forum:
You can reply to topics in this forum