How to rasterize a QGIS vector layer using Python?

106 views Asked by At

I am coding a QGIS plugin and I have a vector layer (named 'parkinho') and I wish to transform it into a raster layer. Currently I have the code:

output_file = r"C:\Users\AlexFidalgoZamikhows\Downloads\raster\raster.tif"
raster_resolution = 10  # Specify the desired resolution in the target CRS
layer = QgsProject.instance().mapLayersByName('parkinho')[0]
extent = layer.extent()  # Get the extent of the vector layer
parameters = {
    "INPUT": layer,
    "FIELD": None,
    "BURN": 1,
    "UNITS": 0,
    "WIDTH": raster_resolution,
    "HEIGHT": raster_resolution,
    "NODATA": 0,
    "OPTIONS": "",
    "DATA_TYPE": 5,
    "INIT": None,
    "INVERT": False,
    "EXTRA": "",
    "EXTENT": extent,  # Provide the extent parameter
    "OUTPUT": output_file
}
result = processing.run("native:rasterize", parameters)

However the size of the raster file, when I upload it back to QGIS, is much larger, when displayed on the map, than the original 'parkinho' vector layer. Not to mention it's kind of distorted. Any tips on how to fix it or where I could get useful information.

The assigned CRS of the 'parkinho' vector layer is:

EPSG: 5875 - SAD69(96) / UTM zone 18S.

I've done it manually with Rasterize and it worked. The logs indicate that the parameters were:

{ 'BURN' : 0, 'DATA_TYPE' : 5, 'EXTENT' : None, 'EXTRA' : '', 'FIELD' : 'id', 'HEIGHT' : 1, 'INIT' : None, 'INPUT' : 'C:/Users/AlexFidalgoZamikhows/Documents/parkinho.shp', 'INVERT' : False, 'NODATA' : 0, 'OPTIONS' : '', 'OUTPUT' : 'TEMPORARY_OUTPUT', 'UNITS' : 1, 'USE_Z' : False, 'WIDTH' : 1 }

However, when I run it through Python with these parameters, I get: raise QgsProcessingException(msg) _core.QgsProcessingException: Unable to execute algorithm Incorrect parameter value for EXTENT

0

There are 0 answers