I have a vector layer projected in WGS84. I would like to use gdal.rasterizeLayer() from the python console to convert it to a raster. I would like to burn values from a field. I followed the gdal cookbook and adjusted the code based on the answer to this thread.

Here is the code I used:

import math
import os
from osgeo import ogr, gdal

# 1. Define pixel_size and NoData value of new raster
NoData_value = -9999
x_res = 0.5 # assuming these are the cell sizes
y_res = 0.5 # change as appropriate
pixel_size = 1

# 2. Filenames for in- and output
_in = "D:\...\\polyTry.shp"
_out = "D:\...\\poly2.tif "

# 3. Open Shapefile
source_ds = ogr.Open(_in)
source_layer = source_ds.GetLayer()
x_min, x_max, y_min, y_max = source_layer.GetExtent()

# 4. Create Target - TIFF
cols = int(math.ceil((x_max - x_min) / x_res ))
rows = int(math.ceil((y_max - y_min) / y_res ))

_raster = gdal.GetDriverByName('GTiff').Create(_out, cols, rows, 1, gdal.GDT_Byte)
_raster.SetGeoTransform((x_min, x_res, 0, y_max, 0, -y_res))
_band = _raster.GetRasterBand(1)

# 5. Rasterize why is the burn value 0... isn't that the same as the background?
 gdal.RasterizeLayer(_raster, [1], source_layer, options = ["ALL_TOUCHED=TRUE", "ATTRIBUTE=id"])

The photo below show the output raster with the green input polygons. Note the Nan values on the left (legend). I also inspected different x, y_resolutions (0.00416, 0.0833333). Additional attempts include creating a floating point and integer raster at both 32 and 64 bit (signed, e.g. gdal.GDT_Float64). All have failed and produced Nan values.

Also note that burn_values = [1] create a raster with all values set to 0. How can it be solved ?



Try to define: _raster = None

..in the end to close the new raster dataset.

  • Welcome to GIS SE. Please, edit and expand your answer. Explain the context and behavior of the code modification proposed by you – aldo_tapia Dec 5 '17 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.