NDVI, SAVI and EVI on One Sentinel-2 Scene: Scaling, Masks and Verified Outputs

Lesson 4 · Practical satellite-data analysis

A vegetation-index comparison needs more than three colourful maps. This worked example puts NDVI, SAVI and EVI on the same valid pixels, records the source and checks the saved rasters. It also makes one deliberate mistake—skipping reflectance scaling—to show why a plausible NDVI result does not verify the rest of a workflow.

Prerequisites: grid alignment and quality masks and missing observations.

The archived sample and its limits

The supplied provenance identifies a Sentinel-2 surface-reflectance chip from Punjab, acquired 13 October 2024, tile 43REQ. It records Earth Engine collection COPERNICUS/S2_SR_HARMONIZED and band order B2, B4, B8, SCL. The 72 × 63 raster uses a ten-metre grid in EPSG:32643. Band descriptions are absent from the TIFF, so the band identities rely on the accompanying provenance.

This reuses an archived chip and sidecar; a fresh upstream export has not been independently reproduced. The sidecar does not record the processing baseline. Crop identity, crop condition and accuracy against field observations are unverified.

All 4,536 cells pass the stored source masks and are SCL 4 or 5: 1,874 vegetation-labelled and 2,662 non-vegetated-land-labelled cells. These are algorithmic labels. This example therefore cannot demonstrate cloud removal. Its SCL was sampled from 20 metres to the ten-metre grid using nearest neighbour; that does not add finer quality information.

Make the calculations comparable

The Earth Engine collection documentation specifies the harmonized value range and reflectance scale of 0.0001. Apply the documented scale once. Do not add a second raw-product offset to values already harmonized by the provider.

Use NDVI = (NIR − Red)/(NIR + Red), SAVI with L = 0.5, and EVI with G = 2.5, C1 = 6, C2 = 7.5 and L = 1. This script retains SCL 4 and 5 and requires finite bands and safe denominators for all three indices. All comparisons then use the same support. The stack is already on one grid; no reprojection is needed here.

NDVI, SAVI and EVI on the same 4536 pixels; shared colour range minus 0.2 to 1. Four EVI cells exceed the upper display limit.
Shared display range −0.2 to 1.0. Four EVI cells exceed the upper colour limit; their numerical values remain unchanged in the outputs.
IndexValid pixelsMeanMinimumMaximum
NDVI4,5360.467969−0.1608500.846559
SAVI4,5360.274651−0.0832900.605836
EVI4,5360.287490−0.0845901.908323

Different means do not identify the most accurate index. Four EVI values exceed 1 and deserve inspection of their spectral inputs and denominator. They are flagged, not silently clipped or interpreted as exceptional crop condition. Passing arithmetic and file checks does not establish physical validity.

A controlled scaling mistake

Now intentionally calculate from the stored integers without multiplying the spectral bands by 0.0001. NDVI is unchanged because this common multiplicative factor cancels. The additive constants in SAVI and EVI do not scale away. On the same 4,536 cells, the incorrect SAVI mean becomes 0.701842 and the incorrect EVI mean becomes 1.200592. These are diagnostics of a processing mistake, not alternate vegetation measurements.

Correctly scaled index values against intentionally unscaled values. NDVI agrees; SAVI and EVI differ substantially.
Horizontal axes show correctly scaled values. Vertical axes intentionally omit scaling. Black lines mark equality; the EVI panel retains extreme diagnostic values.

Download the sample and reproduce the result

Download the archived Sentinel-2 sample TIFF (27,582 bytes). Save it as data/sentinel2_sample.tif. Its anonymous download was checked against the source SHA-256:

bc9cda5e3eaa4edf10759b49e1aac3855bd7674661d9c47854875d6652df4381

Save the following provenance as data/sentinel2_provenance.json. These are archived metadata, not newly verified upstream measurements.

{
  "CLOUDY_PIXEL_PERCENTAGE": 0.000146,
  "MGRS_TILE": "43REQ",
  "system:index": "20241013T053801_20241013T054552_T43REQ",
  "system:time_start": 1728798620888,
  "collection": "COPERNICUS/S2_SR_HARMONIZED",
  "bounds_wgs84": [
    75.8,
    30.9,
    75.8064,
    30.9064
  ],
  "crs": "EPSG:32643",
  "pixel_size_m": 10,
  "band_order": [
    "B2",
    "B4",
    "B8",
    "SCL"
  ],
  "reflectance_scale": 0.0001,
  "reflectance_offset": 0,
  "scl": "Original 20 m classes sampled to 10 m using nearest neighbour.",
  "attribution": "Contains modified Copernicus Sentinel data 2024, processed through Google Earth Engine.",
  "ground_truth": "Land cover and crop status are unverified.",
  "data_terms": "https://sentinels.copernicus.eu/documents/247904/690755/Sentinel_Data_Legal_Notice"
}

Save the script as real_scene.py beside the data folder. Install the tested packages and run it from a writable location. Reruns overwrite the generated files in outputs.

python -m pip install numpy==2.3.5 matplotlib==3.10.8 rasterio==1.4.4
python real_scene.py
"""Offline real-scene index comparison; see README for provenance limits."""
from pathlib import Path
import hashlib, json, csv
import numpy as np
import rasterio
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT = Path(__file__).resolve().parent
OUT = ROOT / 'outputs'
OUT.mkdir(exist_ok=True)
INPUT = ROOT / 'data/sentinel2_sample.tif'
prov = json.loads((ROOT/'data/sentinel2_provenance.json').read_text())
assert prov['band_order'] == ['B2', 'B4', 'B8', 'SCL']
assert prov['collection'] == 'COPERNICUS/S2_SR_HARMONIZED'
assert prov['reflectance_scale'] == .0001 and prov['reflectance_offset'] == 0
with rasterio.open(INPUT) as src:
    stack = src.read().astype('float64')
    source_valid = np.all(src.read_masks() > 0, axis=0)
    profile = src.profile.copy()
    assert src.count == 4 and src.crs.to_epsg() == 32643
    assert src.res == (10, 10)
    shape, transform, crs = src.shape, src.transform, src.crs
    bounds = list(src.bounds)
    descriptions = list(src.descriptions)
blue, red, nir = stack[:3] * .0001
scl = stack[3].astype('uint8')
policy = source_valid & np.isin(scl, [4, 5])

def indices(r, n, b, mask):
    den = [n+r, n+r+.5, n+6*r-7.5*b+1]
    common = mask & np.isfinite(r) & np.isfinite(n) & np.isfinite(b)
    for d in den:
        common &= np.isfinite(d) & (np.abs(d) > 1e-8)
    values = {}
    for name, numerator, denominator in zip(
        ['ndvi','savi','evi'], [n-r, 1.5*(n-r), 2.5*(n-r)], den):
        a = np.full(r.shape, np.nan)
        np.divide(numerator, denominator, out=a, where=common)
        values[name] = a
    return values, common

correct, common = indices(red, nir, blue, policy)
# Intentional diagnostic only: skip reflectance scaling.
wrong, wrong_common = indices(stack[1], stack[2], stack[0], policy)
comparison = common & wrong_common
assert comparison.any()
np.testing.assert_allclose(correct['ndvi'][comparison], wrong['ndvi'][comparison], atol=1e-12)
profile.update(driver='GTiff',count=1,dtype='float32',nodata=-9999,
               photometric='MINISBLACK',interleave='band')
summaries=[]
for name, a in correct.items():
    path=OUT/f'{name}.tif'
    with rasterio.open(path,'w',**profile) as dst:
        dst.write(np.where(common,a,-9999).astype('float32'),1)
    with rasterio.open(path) as src:
        back=src.read(1,masked=True)
        assert src.crs == crs and src.transform == transform and src.shape == shape
        assert np.array_equal(~np.ma.getmaskarray(back),common)
        np.testing.assert_allclose(back.compressed(),a[common],atol=1e-7,rtol=1e-6)
    good=a[comparison]; bad=wrong[name][comparison]
    summaries.append(dict(index=name,valid_pixels=int(common.sum()),
        mean=float(a[common].mean()),minimum=float(a[common].min()),maximum=float(a[common].max()),
        diagnostic_common_pixels=int(comparison.sum()),
        correct_mean_on_diagnostic_support=float(good.mean()),
        unscaled_mean_on_diagnostic_support=float(bad.mean()),
        median_absolute_scaling_error=float(np.median(abs(good-bad))),
        outside_minus1_plus1=int(np.sum((a[common]<-1)|(a[common]>1)))))
with (OUT/'summary.csv').open('w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=summaries[0].keys());w.writeheader();w.writerows(summaries)

fig,axes=plt.subplots(1,3,figsize=(13,5),constrained_layout=True)
cm=plt.get_cmap('YlGn').copy();cm.set_bad('#d1d5db')
for ax,(name,a) in zip(axes,correct.items()):
    im=ax.imshow(a,cmap=cm,vmin=-.2,vmax=1)
    ax.set_title(name.upper());ax.set_xlabel('Column');ax.set_ylabel('Row')
fig.colorbar(im,ax=axes,label='Index value; display range -0.2 to 1.0',shrink=.75,extend='both')
axes[2].text(.02,.02,'4 EVI cells > 1; values retained',transform=axes[2].transAxes,fontsize=10,bbox=dict(facecolor='white',alpha=.9))
fig.suptitle('Sentinel-2 sample | 13 October 2024 | common valid support\nDifferent index values do not establish different accuracy',fontsize=14)
fig.savefig(OUT/'index_maps.png',dpi=180);plt.close(fig)
fig,axes=plt.subplots(1,3,figsize=(13,4),constrained_layout=True)
for ax,row in zip(axes,summaries):
    good=correct[row['index']][comparison];bad=wrong[row['index']][comparison]
    ax.scatter(good,bad,s=3,alpha=.25)
    lo=good.min();hi=good.max()
    ax.plot([lo,hi],[lo,hi],color='black',linewidth=1)
    ax.set_xlim(lo-.02*(hi-lo),hi+.02*(hi-lo))
    ax.set(title=row['index'].upper(),xlabel='Correctly scaled',ylabel='INTENTIONALLY unscaled')
fig.suptitle('Controlled mistake: skip reflectance scaling | identity line in black')
fig.savefig(OUT/'scaling_diagnostic.png',dpi=180);plt.close(fig)
report=dict(input_sha256=hashlib.sha256(INPUT.read_bytes()).hexdigest(),
    shape=list(shape),crs=str(crs),transform=list(transform)[:6],bounds=bounds,
    band_order_source='sidecar provenance; TIFF band descriptions absent',
    original_band_descriptions=descriptions,source_valid_pixels=int(source_valid.sum()),
    scl_counts={str(int(x)):int(y) for x,y in zip(*np.unique(scl,return_counts=True))},
    common_valid_pixels=int(common.sum()),total_pixels=int(common.size),
    valid_fraction=float(common.mean()),summaries=summaries,
    numpy_version=np.__version__,rasterio_version=rasterio.__version__,
    checks='PASS',limitations=[
        'Archived chip and sidecar reused; fresh upstream export not independently reproduced.',
        'Processing baseline not recorded in sidecar; harmonized collection provenance governs scaling.',
        'All cells are SCL 4 or 5: this chip does not demonstrate cloud removal.',
        'Crop identity, crop condition and accuracy against field observations unverified.',
        'SCL was sampled from 20 m to 10 m; no extra quality detail is created.'])
(OUT/'verification.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2))

What the verification establishes

The script executed successfully with the pinned packages. It reopened every output GeoTIFF and checked the CRS, transform, shape, valid mask and pixel values. The output report records the input checksum, SCL counts, valid fraction, diagnostic support and out-of-range counts. This establishes reproducible computation from the archived input; it does not independently establish the original export or validate an agricultural conclusion.

The TIFF source may emit a photometric-layout warning in some readers. The numeric four-band read succeeds. Generated single-band outputs explicitly set grayscale photometric interpretation and passed readback checks.

A useful next question

Before comparing another date, ask whether it has the same valid spatial support and compatible processing history. A changed mean may reflect changed coverage or preprocessing. The next practical topic is inspecting saved outputs in a GIS and checking the georeferencing against the source.

Contains modified Copernicus Sentinel data 2024, processed through Google Earth Engine. Copernicus data terms apply to the source sample. This lesson’s newly written script and original figures are released under the MIT License, copyright 2026 Data Science with DEB. Third-party packages retain their own licenses.

Leave a Comment