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.pyscript from the Vegetation & Field Analysis Pack
Steps
- Load your raster (NDVI, elevation, CHM, or any single-band raster) into QGIS and check (tick) it in the Layers panel.
- Open Plugins → Python Console → Show Editor.
- Paste the script. At the bottom, set:
threshold— the cutoff value (e.g.0.4for NDVI)comparison—'greater_than'or'less_than'nodata— value for masked pixels (default:Nonefor NaN / transparent)
- Click Run.
Common use cases
| Use case | Raster | Threshold | Comparison |
|---|---|---|---|
| Isolate healthy vegetation | NDVI | 0.4 | greater_than |
| Show stressed or bare areas | NDVI | 0.2 | less_than |
| Map low-elevation zones | DTM/DEM | 850 | less_than |
| Show tall canopy only | CHM | 5 | greater_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.pyon NDVI with threshold 0.4 to get a “healthy canopy” highlight layer - Overlay it on your classified CHM from
style_chm.pyto 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.