4

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'})
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Nil
  • 1,517
  • 8
  • 22

1 Answers1

3

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
    processing.run("gdal:rasterize", 
    {'INPUT':QgsProcessingFeatureSourceDefinition(linelayer.id(), True),
    'FIELD':'','BURN':99,'UNITS':1,'WIDTH':1000,'HEIGHT':1000,
    'EXTENT':'360641.64028139116,400174.10607510037,6237176.406709021,6281665.181647016 [EPSG:3006]',
    'NODATA':0,'OPTIONS':'','DATA_TYPE':5,'INIT':None,'INVERT':False,'EXTRA':'','OUTPUT':os.path.join(outfolder,outname)}) 
    linelayer.removeSelection()

enter image description here

BERA
  • 72,339
  • 13
  • 72
  • 161
  • Can I still make it work if the linelayer is a memory layer? – Nil May 04 '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 04 '20 at 13:41
  • It works when I add my memory layer to map QgsProject.instance().addMapLayer(my_memory_layer, False) – Nil May 04 '20 at 13:47