I have a vector layer which is consists of channels in a watershed. I want to rasterize each individual line in the layer separately in PyQGIS. I could not manage to loop through in the layer and rasterize. I am trying to do it with gdal:rasterize. I have seen that one can add -where in gdal:rasterize but I still couldn't make it work.

How can I do it?

My goal is to rasterize a channel and use native:rasterlayerzonalstats to get the max for each channel in the layer. Another option is buffering the line layer but I want to rasterize and go that way.

for feat in vlyr_ger.getFeatures():
    objectid = feat['OBJECTID']
    res88 = processing.run ("gdal:rasterize", {
            'INPUT': vlyr_ger,  # already vector layer
            'WHERE': 'OBJECTID='+ str(objectid),
            'FIELD': None,
            'BURN': 1,  # Fixed value to burn
            'UNITS': 1,  # Georeferenced units
            'WIDTH': cellsize,
            'HEIGHT': cellsize,
            'EXTENT': rlyr_demFilled,
            'NODATA': 0,
            'OPTIONS': '',
            'DATA_TYPE': 5,  # Float32
            'INIT': None,
            'INVERT': False,
            'EXTRA': '-tap',
            'OUTPUT': 'TEMPORARY_OUTPUT'})

You will need to adjust the parameters:

import os

outfolder = r'C:\GIS\data\testdata\outrasters'
linelayer = QgsProject.instance().mapLayersByName('testlines')[0]

for e, line in enumerate(linelayer.getFeatures()):
    linelayer.select(line.id()) #Select this line
    outname = 'Line_{}.tif'.format(e)

    #Execute algorihtm on selected line: QgsProcessingFeatureSourceDefinition: https://gis.stackexchange.com/questions/311336/run-pyqgis-algorithm-on-selected-features-in-layer
    {'INPUT':QgsProcessingFeatureSourceDefinition(linelayer.id(), True),
    'EXTENT':'360641.64028139116,400174.10607510037,6237176.406709021,6281665.181647016 [EPSG:3006]',

enter image description here

  • Can I still make it work if the linelayer is a memory layer? – Nil May 4 '20 at 13:39
  • It didn't work out. I get an error that says "Could not load source layer for INPUT: Clipped_121f3dc8_1870_4174_94d5_b98f380e34ab not found". Clipped_121f3dc8_1870_4174_94d5_b98f380e34ab is a memory layer. – Nil May 4 '20 at 13:41
  • It works when I add my memory layer to map QgsProject.instance().addMapLayer(my_memory_layer, False) – Nil May 4 '20 at 13:47

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.