QGIS Script · Python
Canopy NDVI Median Calculator
Takes your input polygon layer — tree crown outlines, plot zones, or any annotation — and outputs a GeoJSON copy with a new NDVI_median field added to each feature. Only canopy pixels are sampled, not bare soil or gaps, so the figure reflects actual vegetation health. Feed the output into the Layer Classifier to colour-code trees from stressed to healthy in one more step.
What you get
canopy_ndvi_median_calc.pyWhat it does
Canopy-only NDVI sampling
Samples NDVI values from within each polygon but only at pixels where the canopy mask equals 1 — ignoring bare soil, paths, and open areas that would otherwise dilute the reading.
Median per polygon
Computes the median of the canopy-only NDVI values within each feature — more robust to outliers than mean, giving a stable health figure per tree or plot.
Output is a vector GeoJSON
The output is a copy of your input polygon layer saved as a GeoJSON file, with a new NDVI_median attribute added to each feature. Your original file is not modified.
Works with any polygon annotations
Input can be tree crown outlines digitised by hand, auto-detected crown polygons, plot zones, or orchard block boundaries — any polygon layer that overlaps the NDVI and canopy mask rasters.
Requires: Canopy Mask Generator
This script needs a canopy_mask raster layer in your QGIS project before it will run. Generate it from your DSM and DTM using the Canopy Mask Generator — takes under a minute and only needs to be done once per survey.
Next step: Layer Classifier
The output GeoJSON has an NDVI_median field but no visual styling yet. The Layer Classifier applies a graduated yellow → green colour ramp to any numeric field — run it on your output to instantly see which trees or plots are stressed and which are healthy.
How to use it
- 1
Run
generate_canopy_mask.pyfirst to create thecanopy_masklayer. - 2
Load your polygon plot layer and click it to make it the active layer.
- 3
Check (tick) the
canopy_maskraster and your NDVI raster in the Layers panel. - 4
Open Plugins → Python Console → Show Editor.
- 5
Paste the script and click Run.
Requirements
- QGIS 3.28 or newer
- numpy, rasterio — bundled with QGIS
- Active polygon layer (plot zones)
- canopy_mask raster (from generate_canopy_mask.py)
- NDVI raster — layer name contains "ndvi"
Also in the Vegetation & Field Analysis Pack
Get all 6 vegetation scripts for $70 — save $50 vs buying individually.