QGIS Script · Python
Canopy Mask Generator
Creates a binary raster (1 = canopy, 0 = ground) by subtracting the DTM from the DSM. Any pixel where DSM − DTM exceeds 0.1 m is classified as canopy. The output is used directly by the Canopy NDVI Calculator to ensure NDVI is sampled only where vegetation exists — not bare soil within the plot boundary.
What you get
generate_canopy_mask.pyWhat it does
Binary canopy / ground raster
Output pixel is 1 where DSM − DTM > 0.1 m (canopy or structure), 0 everywhere else (bare ground, path, open sky).
0.1 m height threshold
The 0.1 m minimum filters sub-10 cm noise from DTM rounding, preventing false canopy classifications on flat ground.
Foundation for NDVI analysis
The canopy_mask layer is the required input for canopy_ndvi_median_calc.py — run this first before computing per-plot NDVI.
Saved alongside DSM
Output canopy_mask.tif is saved in the same directory as the DSM and loaded into the QGIS project immediately.
Why the mask matters for NDVI
Standard zonal NDVI statistics sample every pixel inside a plot boundary — including bare soil between rows, paths, and gaps in the canopy. In plantation estates and coffee estates where shade trees leave significant open ground, this dilutes the NDVI reading and makes healthy blocks appear stressed. The canopy mask filters out those non-vegetation pixels before any NDVI computation, giving you a figure that reflects only the trees you are actually assessing.
Next step: Canopy NDVI Calculator
Once the mask is generated, feed it into the Canopy NDVI Calculator alongside your NDVI raster and plot polygons to get per-plot vegetation health scores — canopy pixels only, no soil contamination.
How to use it
- 1
Load your DSM and DTM rasters into QGIS. Layer names must contain
_dsmand_dtm. - 2
Check (tick) both layers in the Layers panel.
- 3
Open Plugins → Python Console → Show Editor.
- 4
Paste the script and click Run.
Requirements
- QGIS 3.28 or newer
- numpy, rasterio — bundled with QGIS
- DSM raster — layer name contains "_dsm"
- DTM raster — layer name contains "_dtm"
Also in the Vegetation & Field Analysis Pack
Get all 6 vegetation scripts for $40 — save $20 vs buying individually.