I am working on a python script in QGIS and am trying to rasterize a vector layer containing a single polygon. I am using QGIS 3.2 and am encountering the following traceback, that I am unable to deal with:
File "C:\OSGEO4~1\apps\Python36\lib\code.py", line 91, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 118, in <module>
File "C:\OSGEO4~1\apps\Python36\lib\site-packages\osgeo\gdal.py", line 2738, in RasterizeLayer
return _gdal.RasterizeLayer(*args, **kwargs)
TypeError: in method 'RasterizeLayer', argument 4 of type 'OGRLayerShadow *'
The following code generates the error above (line 118 is the last line):
# 5. rasterize vector layer and save as tiff
gdal.UseExceptions()
# a) define resolution and NoData value of new raster
x_res = 0.001 # degree per pixel
y_res = 0.001 # smaller value gives larger tiffs (higher resolution)
NoData_value = -9999
# b) filename for output
_out = r"D:/asdf23.tiff"
# c) get extent of layer
qgsRect = layer.extent()
x_min = qgsRect.xMinimum(); x_max = qgsRect.xMaximum()
y_min = qgsRect.yMinimum(); y_max = qgsRect.yMaximum()
# d) create target - TIFF
nbPixelX = int( (x_max - x_min) / x_res )
nbPixelY = int( (y_max - y_min) / y_res )
srs = layer.sourceCrs()
raster = gdal.GetDriverByName('GTiff').Create(_out, nbPixelX, nbPixelY, 1, gdal.GDT_Int32)
raster.SetProjection(srs.toWkt())
raster.SetGeoTransform((x_min, x_res, 0, y_max, 0, -y_res))
band = raster.GetRasterBand(1)
band.SetNoDataValue(NoData_value)
# e) Rasterize
err = gdal.RasterizeLayer(raster, [1], layer, burn_values=[102])
Any hints and tips are greatly appreciated, as I am running out of ideas. Thank you!
Finally solved it by using the processing module:
import processing
extent = layer.extent()
xmin = extent.xMinimum()
xmax = extent.xMaximum()
ymin = extent.yMinimum()
ymax = extent.yMaximum()
processing.run("gdal:rasterize",
{"INPUT":layer,
"FIELD":"myElev",
"UNITS":0,
"WIDTH":300,
"HEIGHT":300,
"EXTENT":"%f,%f,%f,%f"% (xmin, xmax, ymin, ymax),
"NODATA":0,
"DATA_TYPE":1,
"INVERT":0,
"OUTPUT":"D:/myPath/file.tif"})
Hope that helps someone running into the same issue. Cheers!