Filter a Raster by Threshold in QGIS (NDVI Masking and More)

QGIStutorialrasterNDVImaskingPython

Sometimes you want to isolate only the pixels in a raster that meet a condition — for example, keeping only healthy vegetation (NDVI > 0.4) and masking out everything else. This script does that in one step for any single-band raster.

What it does

The raster_mask_generator.py script creates a filtered copy of a raster where only pixels that pass a threshold test are kept. All other pixels are set to NoData, making them transparent in QGIS.

Two comparison modes:

  • greater_than — keeps pixels above the threshold (e.g. NDVI > 0.4 → healthy vegetation only)
  • less_than — keeps pixels below the threshold (e.g. elevation < 850 m → low-lying areas only)

Output: {input_name}_mask_{comparison}{threshold}_{nodata}.tif saved in the same directory as the input, loaded into the QGIS project.

What you need

  • QGIS 3.28 or newer
  • QGIS processing framework (bundled)
  • The first checked raster layer in the Layers panel (any single-band raster)
  • The raster_mask_generator.py script from the Vegetation & Field Analysis Pack

Steps

  1. Load your raster (NDVI, elevation, CHM, or any single-band raster) into QGIS and check (tick) it in the Layers panel.
  2. Open Plugins → Python Console → Show Editor.
  3. Paste the script. At the bottom, set:
    • threshold — the cutoff value (e.g. 0.4 for NDVI)
    • comparison'greater_than' or 'less_than'
    • nodata — value for masked pixels (default: None for NaN / transparent)
  4. Click Run.

Common use cases

Use caseRasterThresholdComparison
Isolate healthy vegetationNDVI0.4greater_than
Show stressed or bare areasNDVI0.2less_than
Map low-elevation zonesDTM/DEM850less_than
Show tall canopy onlyCHM5greater_than

Combining with other scripts

The output of this script can be used as an additional visual layer on top of your main analysis. For example:

  • Run raster_mask_generator.py on NDVI with threshold 0.4 to get a “healthy canopy” highlight layer
  • Overlay it on your classified CHM from style_chm.py to see where healthy vegetation and tall trees overlap

Get the script

raster_mask_generator.py is part of the Vegetation & Field Analysis Pack — six vegetation analysis scripts for QGIS at $40 USD.