Lesson 3 · Practical satellite-data analysis
A mean NDVI of 0.625 becomes 0.15625 without changing any valid observation. How? By replacing missing pixels with zero before averaging. This synthetic example shows how to keep quality filtering, data validity and the denominator check together.
Start with lesson two’s grid-alignment example. Here we assume all input arrays already describe the same cells.
Follow the pixels
Page contents

Our explicit land policy retains SCL classes 4 and 5. Six cells qualify initially. One has no NIR observation and another has a zero denominator; four remain. Three have NDVI 0.5 and one has NDVI 1.0. Their mean is (0.5 + 0.5 + 0.5 + 1.0) / 4 = 0.625.
If all twelve excluded cells become zero, the sum is divided by sixteen and the mean becomes 0.15625. That is a different calculation, not evidence that vegetation has declined. Report the valid fraction—25% in this example—alongside the summary. It describes coverage, not representativeness.
Separate policy from validity
The official Copernicus SCL table identifies scene classes. Codes 4 and 5 are vegetation and non-vegetated land. Keeping only these is a conservative teaching policy for a land analysis, not a universal clear-sky rule. Water can be a valid observation even when it is outside this analysis.
SCL estimates can be wrong. Inspect the imagery and processing metadata; class-2 naming has changed across baselines. Resampling its categorical grid to match another grid does not add finer quality information. Use nearest neighbour for that alignment and inspect boundaries.
Then check per-band validity and the index denominator. Do not use red != 0 as a universal validity rule: in this constructed example red is genuinely zero in a retained cell, while NIR is 0.4 and NDVI is 1.0. Actual products require their declared nodata, masks, scaling and offsets.
Run the complete example
Save the source below as masking_demo.py in a writable folder. It starts with synthetic reflectance arrays, not raw Sentinel-2 digital numbers. It creates a teaching figure, a GeoTIFF and a verification report. Rerunning overwrites generated files in its outputs folder.
python -m pip install numpy==2.3.5 matplotlib==3.10.8 rasterio==1.4.4
python masking_demo.py
"""Synthetic validity-mask teaching demonstration."""
import numpy as np
scl = np.array([
[4, 4, 5, 6],
[7, 8, 9, 10],
[3, 2, 0, 1],
[11, 4, 5, 4],
], dtype="uint8")
red = np.full((4, 4), 0.2, dtype="float64")
nir = np.full((4, 4), 0.6, dtype="float64")
# Explicit teaching edge cases; these are not raw Sentinel-2 DN.
red[3, 1], nir[3, 1] = 0.0, 0.4
red[3, 2], nir[3, 2] = -0.1, 0.1
nir[3, 3] = np.nan
# Conservative LAND teaching policy: retain SCL 4 and 5 only.
# Excluding water does not mean water is an erroneous observation.
land_policy = np.isin(scl, [4, 5])
denom = nir + red
valid = (land_policy & np.isfinite(red) & np.isfinite(nir)
& (np.abs(denom) > 1e-8))
ndvi = np.full(red.shape, np.nan, dtype="float64")
np.divide(nir - red, denom, out=ndvi, where=valid)
assert valid.sum() == 4
assert np.isclose(np.nanmean(ndvi), 0.625)
assert np.isclose(ndvi[3, 1], 1.0) # red=0 alone is not nodata
assert np.isnan(ndvi[3, 2]) # denominator is zero
assert np.isnan(ndvi[3, 3]) # missing NIR
assert np.isclose(np.nan_to_num(ndvi, nan=0.0).mean(), 0.15625)
print("Valid cells:", int(valid.sum()), "of", valid.size)
print("Valid fraction:", float(valid.mean()))
print("Mean over valid cells:", float(np.nanmean(ndvi)))
print("Wrong zero-filled mean:", float(np.nan_to_num(ndvi).mean()))
from pathlib import Path
import json
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, BoundaryNorm
out = Path(__file__).resolve().parent / "outputs"
out.mkdir(exist_ok=True)
fig, axes = plt.subplots(1, 3, figsize=(14, 5), constrained_layout=True)
colors = ["#111827","#6b7280","#92400e","#a16207","#15803d","#d6b87c",
"#0284c7","#a855f7","#cbd5e1","#ffffff","#67e8f9","#f9a8d4"]
axes[0].imshow(scl, cmap=ListedColormap(colors), norm=BoundaryNorm(np.arange(-.5,12.5),12))
axes[1].imshow(valid, cmap=ListedColormap(["#e5e7eb","#15803d"]), vmin=0,vmax=1)
cm = plt.get_cmap("YlGn").copy()
cm.set_bad("#e5e7eb")
im=axes[2].imshow(np.ma.masked_invalid(ndvi),cmap=cm,vmin=0,vmax=1)
for ax,title in zip(axes,["SCL class codes","Valid for this land policy","NDVI: valid cells only"]):
ax.set_title(title,fontsize=14)
ax.set_xticks(range(4));ax.set_yticks(range(4))
ax.set_xlabel("Column");ax.set_ylabel("Row")
for r in range(4):
for c in range(4):
axes[0].text(c,r,str(scl[r,c]),ha="center",va="center",color="black",
bbox=dict(facecolor="white",alpha=.8,edgecolor="none"))
axes[1].text(c,r,"Keep" if valid[r,c] else "Exclude",ha="center",va="center",
fontsize=10,color="white" if valid[r,c] else "black")
axes[2].text(c,r,f"{ndvi[r,c]:.2f}" if valid[r,c] else "Missing",
ha="center",va="center",fontsize=10,
color="white" if valid[r,c] and ndvi[r,c]>.7 else "black")
fig.colorbar(im,ax=axes[2],shrink=.65,label="Synthetic NDVI")
fig.suptitle("Synthetic teaching data | 4 of 16 valid | mean 0.625 | zero-filled mean 0.15625",fontsize=15)
fig.savefig(out/"masking_walkthrough.png",dpi=180)
plt.close(fig)
report={"synthetic": True,"total_pixels":16,"policy_candidates":int(land_policy.sum()),
"valid_pixels":int(valid.sum()),"valid_fraction":float(valid.mean()),
"valid_mean":float(np.nanmean(ndvi)),
"wrong_zero_filled_mean":float(np.nan_to_num(ndvi).mean()),
"numpy_version":np.__version__,"assertions":"PASS"}
(out/"verification.json").write_text(json.dumps(report,indent=2))
import rasterio
from rasterio.transform import from_origin
transform = from_origin(500000, 3000000, 10, 10)
saved = np.where(valid, ndvi, -9999).astype("float32")
with rasterio.open(out/"masked_ndvi.tif","w",driver="GTiff",height=4,width=4,
count=1,dtype="float32",crs="EPSG:32646",
transform=transform,nodata=-9999) as dst:
dst.write(saved,1)
with rasterio.open(out/"masked_ndvi.tif") as src:
back=src.read(1,masked=True)
assert src.transform == transform
assert src.crs.to_epsg() == 32646
assert back.count() == 4
assert np.array_equal(~np.ma.getmaskarray(back),valid)
assert np.isclose(back.mean(),0.625)
assert back[3,1] == 1.0
report["rasterio_version"]=rasterio.__version__
report["geotiff_readback"]="PASS"
(out/"verification.json").write_text(json.dumps(report,indent=2))
Expected checks
The source was executed with NumPy 2.3.5, Matplotlib 3.10.8 and Rasterio 1.4.4. All assertions passed, including reopening the GeoTIFF and checking that exactly four cells remain valid, its mean is 0.625 and the saved geometry matches the declared grid.
Valid cells: 4 of 16
Valid fraction: 0.25
Mean over valid cells: 0.625
Wrong zero-filled mean: 0.15625
Use this carefully with a real scene
Keep a documented analysis policy. Combine it with source masks and finite-value checks after alignment. Inspect cloud edges, shadows and remaining gaps. When comparing dates, report each date’s valid coverage and check whether changing spatial coverage affects the comparison. A complete-looking map is not the goal; a defensible set of observations is.
This demonstration establishes the arithmetic and mask handling only. It does not establish cloud-detection accuracy, crop identity or crop condition. A field-wide mean from four selected pixels may be unrepresentative.
Try it yourself
Change the policy to retain water as well, explain the new valid count, and calculate the mean over that new population. Keep the original result separately. Then change the missing NIR cell to a valid observation and predict the new denominator before running the code.
Code and original teaching figures: MIT License, copyright 2026 Data Science with DEB. Third-party software retains its own licenses. Sources: Copernicus S2 Processing and Rasterio reprojection.
Next in the sequence: combine scaling, alignment and quality checks in a documented real-scene comparison.
Continue to lesson four: combine scaling, masks and output verification on an archived Sentinel-2 scene. Includes a freely downloadable sample and a controlled scaling-error diagnostic.