TransWikia.com

QGIS: Creating contours at a certain elevation from DEM that match a value from a polygon layer

Geographic Information Systems Asked by NinjaNumbat on May 7, 2021

Trying to create contours from a 1m DEM at certain levels only when the contours fall inside a polygon with an field containing the desired contour elevation value.

See images below. For example in the western area I only want to show a -11.8m contour. The polygon has a field ‘Critical_Depth’ and value of -11.8. I’ve already used the aggregate function to colour the soundings related to a ‘Critical_Depth’ value. Is it possible to do something similar for contouring? Ideally if I need to adjust the critical depth of an area I would like the label colours and red contour lines to automatically update. I have the labels working, just need to figure out a solution for the contours.

0.1m contours

Desired result

One Answer

This is kind of a workaround, dont know if it is faster than creating contours for the entire raster every 0.1 m then intersect and selecting by polygon attribute:

For each feature/polygon in the vector layer:

  • Clip raster by mask layer, where the mask layer is each selected polygon
  • Execute contour with the clipped raster as input and by reading interval from the polygon
  • Store output in a list

Then merge all outputs in the list.

vlyr = QgsProject.instance().mapLayersByName('New scratch layer')[0]
height_field = 'height'
rlyr = QgsProject.instance().mapLayersByName('DEM')[0]

contourlist = []
for f in vlyr.getFeatures():
    vlyr.select(f.id())
    clipped_raster = processing.run("gdal:cliprasterbymasklayer", 
        {'INPUT':rlyr,'MASK':QgsProcessingFeatureSourceDefinition(vlyr.source(), 
            selectedFeaturesOnly=True, featureLimit=-1, 
            geometryCheck=QgsFeatureRequest.GeometryAbortOnInvalid),'SOURCE_CRS':None,
            'TARGET_CRS':None,'NODATA':None,'ALPHA_BAND':False,'CROP_TO_CUTLINE':True,
            'KEEP_RESOLUTION':False,'SET_RESOLUTION':False,'X_RESOLUTION':None,'Y_RESOLUTION':None,'MULTITHREADING':False,'OPTIONS':'','DATA_TYPE':0,'EXTRA':'','OUTPUT':'TEMPORARY_OUTPUT'})['OUTPUT']
    temp_contour = processing.run("gdal:contour", 
        {'INPUT':clipped_raster,'BAND':1,'INTERVAL':[f[height_field] for f in vlyr.getSelectedFeatures()][0], 'FIELD_NAME':'ELEV',
            'CREATE_3D':False,'IGNORE_NODATA':False,'NODATA':None,'OFFSET':0,
            'EXTRA':'','OUTPUT':'TEMPORARY_OUTPUT'})['OUTPUT']
    contourlist.append(temp_contour)
    vlyr.deselect(f.id())

processing.runAndLoadResults("native:mergevectorlayers", {'LAYERS':['{0}|layername={1}'.format(c, 'contour') for c in contourlist],
        'CRS':None,'OUTPUT':'TEMPORARY_OUTPUT'})

enter image description here

Answered by BERA on May 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP