Machine Learning is learning from data and identifying the trend, pattern and insights from data in hand. It is gaining very fast popularity across the industry sectors. Machine Learning skill is an essential one nowadays to analyze a large amount of data to come up with some robust model thus enabling quick decision making and policy optimization.
A plausible-looking NDVI map can still come from the wrong bands, an inappropriate scale, a misleading mask or an incorrectly exported file. This worked checklist shows what to inspect before interpreting or sharing the result.
The example uses our archived Sentinel-2 teaching sample. It demonstrates processing consistency; crop identity, crop condition and independent ground-position accuracy have not been established.
1. Confirm physical band identity
The prepared stack has four bands in the declared order blue (B2), red (B4), near infrared (B8) and scene classification (SCL). Its band descriptions are empty. Four bands alone cannot prove their identity. Confirm the order from your export code and provenance. A confirmation flag records your acknowledgement; it is not an automatic identification test.
2. Apply the product-specific scale and offset
For this archived harmonized teaching sample, the reflectance conversion is stored value × 0.0001, with zero offset. These are sample-specific settings. Do not assume they apply to every product. A common multiplicative scale cancels algebraically in NDVI when both bands use that scale, no additive offset and a nonzero denominator. It does not generally cancel in SAVI or EVI because of their additive constants.
3. State your validity policy and count observations
The private workflow candidate retains SCL classes 4, 5 and 6: vegetation, bare soil and water. It also uses source masks, a conservative reflectance interval of [0,1] and index-specific denominator checks. Water is included, so this is not automatically a vegetation-only analysis. The interval is a processing convention that can exclude values from otherwise valid products; evaluate it for your application. SCL screening cannot guarantee every retained pixel is uncontaminated.
The saved sample report retains 4,536 cells in each index, with no exclusions for this tiny sample. That result does not demonstrate effective cloud removal on a challenging scene. Missing values must remain distinguishable from valid zeros.
What the sample actually shows
Reopened output means are NDVI 0.467969, SAVI 0.274651 and EVI 0.287490 (rounded). These are results from one archived teaching chip, not field-average crop-health estimates. A difference between index means does not establish comparative accuracy.
Archived teaching-sample results. Tap for full size. Reproducibility checks do not establish scientific accuracy.
4. Reopen the file you intend to share
Check the saved raster, rather than relying only on an in-memory array. This sample has 63 columns, 72 rows, EPSG:32643 and 10 m pixels. Compare its CRS, transform, bounds, dimensions, mask and values with the intended grid and result. Grid agreement with an archived input is an internal consistency check, not an independent validation of geographic accuracy.
On 1 December 2026, the three archived output files matched their recorded SHA-256 hashes. Separate NumPy expressions reproduced their pixel values within float32 tolerance, and their CRS and transforms matched the input. This was an archived-output replay on the current host, not a fresh Windows installation test of the workflow wrapper.
A small read-only inspector
Save the following as inspect_index.py, install NumPy and Rasterio in your chosen Python environment, and run python inspect_index.py path/to/ndvi.tif. It reads band one, respects its mask, and excludes non-finite values from the summary. It reports stored values; it does not apply scale or offset automatically. Displayed metadata still needs comparison with your expected source.
import sys
import numpy as np
import rasterio
with rasterio.open(sys.argv[1]) as src:
band = src.read(1, masked=True)
values = band.compressed()
finite = values[np.isfinite(values)]
print("shape:", src.shape, "bands:", src.count)
print("CRS:", src.crs)
print("transform:", src.transform)
print("bounds:", src.bounds)
print("dtype / nodata:", src.dtypes[0], src.nodata)
print("scale / offset metadata:", src.scales[0], src.offsets[0])
print("unmasked / finite:", values.size, finite.size)
if finite.size:
print("stored min / mean / max:",
finite.min(), finite.mean(dtype=np.float64), finite.max())
else:
print("No finite unmasked values")
5. Investigate unusual values before adjusting colours
The sample EVI maximum is approximately 1.9083 and remains in the numerical output. A display capped at 1 can conceal values above the selected colour range without changing the file. Inspect the inputs, formula denominator and screening policy. Do not silently clip values and present the result as a quality improvement.
What this workflow does—and does not—establish
The current private Windows release candidate adds prepared-stack preflight, explicit assumptions, exclusion counts, staged output generation and local HTML/JSON evidence. Its saved report is the example reviewed here. It has not been independently tested by a new user, and a wholly clean installation remains pending. It is not a validated crop-health, yield or insurance decision system. No new product release or purchase recommendation is announced in this lesson.
Your five-check record
Before sharing a map, record: confirmed band identity; scale and offset with their source; the validity policy and usable counts; reopened geometry, masks and values; and unusual values requiring investigation. Keep checked facts separate from assumptions.
Continue learning
Use the existing learning path for the detailed alignment, missing-pixel, real-scene, GeoTIFF and QGIS examples.
Sources and provenance
Official Rasterio documentation on nodata masks and georeferencing supports the mask/geometry inspection steps. Sample provenance and its unresolved limitations are documented in the real-scene lesson. Video narration is synthetic (stock Kokoro bm_george); the calculations and checks described above were executed as recorded.
A smooth NDVI line can hide a long period without usable observations. Before interpreting a seasonal curve, check which dates contain measurements, how far apart they are and whether any plotted values were estimated.
In lesson six, we checked where a raster places its values. Now we check when measurements exist. This free article uses six deliberately constructed dates, not real satellite observations. No video accompanies it.
Six dates, four observations
Imagine that each row represents one scheduled observation of the same area. Two dates have no usable value. A missing value is different from an observed NDVI of zero: zero is a possible numerical measurement and must remain valid when its quality checks pass. See the masking lesson for the spatial version of this distinction.
Date (2026)
Synthetic NDVI
Status
1 June
0.20
Observed
6 June
0.30
Observed
11 June
Missing
No observation
26 June
Missing
No observation
1 July
0.65
Observed
6 July
0.50
Observed
The arithmetic mean of the four observed values is (0.20 + 0.30 + 0.65 + 0.50) / 4 = 0.4125. Incorrectly substituting two zeros changes the denominator to six and gives 0.2750. That drop is introduced by data handling; it is not observed vegetation change.
Show the gap on a calendar axis
Synthetic teaching data. Both panels use the same date positions and vertical limits. In A, crosses below zero mark missing dates; they are not NDVI measurements. In B, crosses at zero mark the deliberately incorrect replacements. Lines guide the eye and do not establish values between observations.
The horizontal axis uses actual elapsed calendar time. There are 25 days between the valid measurements on 6 June and 1 July. Equally spacing the six rows would conceal their unequal timing. Dropping missing rows and joining the remaining points would also draw an uninterrupted line across that interval. In the plotting script, missing values remain NaN so the line breaks.
Interpolation creates an estimate
Linear interpolation assumes a straight path between two valid endpoints. It does not recover a measurement that was never observed. Here the example permits interpolation only when the bracketing valid observations are at most ten days apart. Both missing dates lie inside a 25-day bracket, so they stay missing. The ten-day limit is an arbitrary teaching rule, not a recommended satellite, crop or operational threshold.
A real rule needs a stated purpose, temporal dynamics and evidence appropriate to the use. A smooth estimated curve must be labelled separately from observations. Avoid extrapolating beyond the first or last valid measurement unless you have an explicit model and evidence for doing so.
Run the reproducible example
Save the first script as time_series_gaps.py in a writable folder. It uses only Python’s standard library and writes synthetic_observations.csv and verification.json beside itself. Running it again overwrites those generated outputs. The script is a transparent teaching example for these fixed, sorted dates, not a general production time-series processor.
python time_series_gaps.py
"""Synthetic teaching experiment: gaps are not zero observations.
No satellite inputs, crop labels, or interpolation accuracy claims.
Run with Python 3.10+; standard library only.
"""
from datetime import date
from pathlib import Path
import csv
import json
import math
ROOT = Path(__file__).resolve().parent
rows = [
("2026-06-01", 0.20),
("2026-06-06", 0.30),
("2026-06-11", None),
("2026-06-26", None),
("2026-07-01", 0.65),
("2026-07-06", 0.50),
]
valid = [(date.fromisoformat(d), v) for d, v in rows if v is not None]
observed_mean = sum(v for _, v in valid) / len(valid)
wrong_zero_mean = sum(v or 0 for _, v in rows) / len(rows)
gaps = [(b[0] - a[0]).days for a, b in zip(valid, valid[1:])]
assert math.isclose(observed_mean, 0.4125)
assert math.isclose(wrong_zero_mean, 0.275)
assert max(gaps) == 25
# Ten days is an arbitrary teaching rule, not a crop-specific recommendation.
max_bracket_days = 10
output = []
for day_text, value in rows:
day = date.fromisoformat(day_text)
estimate = None
status = "observed" if value is not None else "missing"
if value is None:
left = [r for r in valid if r[0] < day]
right = [r for r in valid if r[0] > day]
if left and right:
a, b = left[-1], right[0]
width = (b[0] - a[0]).days
if width <= max_bracket_days:
estimate = a[1] + (b[1] - a[1]) * (day - a[0]).days / width
status = "modelled_linear"
else:
status = "missing_long_gap"
output.append((day_text, value, estimate, status))
assert all(r[2] is None for r in output)
assert sum(r[3] == "missing_long_gap" for r in output) == 2
with (ROOT / "synthetic_observations.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["date", "observed_ndvi", "modelled_ndvi", "status"])
writer.writerows(output)
result = {
"synthetic": True,
"scheduled_rows": len(rows),
"valid_observations": len(valid),
"observed_sample_mean": observed_mean,
"incorrect_zero_filled_sample_mean": wrong_zero_mean,
"largest_valid_observation_gap_days": max(gaps),
"illustrative_max_interpolation_bracket_days": max_bracket_days,
"long_gap_rows_left_missing": 2,
"limitation": "Sample means are not time-weighted seasonal means. No real crop or satellite validation.",
}
(ROOT / "verification.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
print(json.dumps(result, indent=2))
Expected checks: six scheduled rows, four valid observations, mean approximately 0.4125, incorrect zero-filled mean approximately 0.275, largest valid-observation gap 25 days, and two long-gap rows left missing. The assertions passed with Python 3.14. Floating-point output may display 0.27499999999999997 instead of 0.275.
Recreate the figure
Save this second script as plot_time_series.py in the same folder. Run the first script before it. The plot was generated with Matplotlib 3.11.0 and reviewed at 360 pixels wide; a crowded annotation was moved before publication. The script writes PNG, SVG and a narrow review copy. Matplotlib’s dependencies include Pillow, used for that review copy.
"""Plot synthetic observations using real date spacing; no long-gap bridge."""
from datetime import date
from pathlib import Path
import csv
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
root = Path(__file__).resolve().parent
with (root / "synthetic_observations.csv").open(encoding="utf-8") as f:
records = list(csv.DictReader(f))
dates = [date.fromisoformat(r["date"]) for r in records]
observed = [float(r["observed_ndvi"]) if r["observed_ndvi"] else math.nan for r in records]
wrong = [v if math.isfinite(v) else 0.0 for v in observed]
plt.rcParams.update({"font.size": 15, "axes.titlesize": 18, "axes.labelsize": 15})
fig, axes = plt.subplots(2, 1, figsize=(7.2, 9.2), sharex=True, sharey=True, layout="constrained")
for ax in axes:
ax.set_ylim(-0.08, 0.9)
ax.set_yticks([0, 0.3, 0.6, 0.9])
ax.grid(axis="y", alpha=0.25)
ax.set_ylabel("Synthetic NDVI")
ax.spines[["top", "right"]].set_visible(False)
axes[0].plot(dates, observed, "o-", color="#126B5E", linewidth=2.5, markersize=9)
axes[0].axvspan(dates[1], dates[4], color="#D89417", alpha=0.10)
axes[0].annotate("25 days between\nvalid observations", xy=(mdates.date2num(dates[1]) + 12.5, 0.46), ha="center", fontsize=15)
axes[0].scatter([dates[2], dates[3]], [-0.035, -0.035], marker="x", color="#555555", s=70)
axes[0].text(0.02, 0.96, "4 observed samples; mean = 0.4125", transform=axes[0].transAxes, va="top", fontsize=14)
axes[0].set_title("A. Keep missing dates missing", loc="left", pad=12)
axes[1].plot(dates, wrong, "o--", color="#A6382F", linewidth=2, markersize=8)
axes[1].scatter([dates[2], dates[3]], [0, 0], marker="X", color="#A6382F", s=120, zorder=5)
axes[1].text(0.02, 0.96, "6 values after zero-fill; mean = 0.2750", transform=axes[1].transAxes, va="top", fontsize=14)
axes[1].set_title("B. Incorrectly replace missing with zero", loc="left", pad=12)
axes[1].set_xticks([dates[i] for i in [0, 2, 3, 5]])
axes[1].xaxis.set_major_formatter(mdates.DateFormatter("%d %b"))
axes[1].set_xlabel("2026 calendar dates (unequal spacing)")
fig.suptitle("Missing is not zero", fontsize=22, fontweight="bold")
fig.savefig(root / "time_series_gaps.png", dpi=200)
fig.savefig(root / "time_series_gaps.svg")
# Narrow-size QA artifact, not a separate data transformation.
from PIL import Image
with Image.open(root / "time_series_gaps.png") as im:
im.resize((360, round(im.height * 360 / im.width)), Image.Resampling.LANCZOS).save(root / "time_series_gaps_360.png")
print("Figure saved; Matplotlib", matplotlib.__version__)
What the mean cannot establish
The value 0.4125 is an observed-sample mean. It is not automatically a time-weighted seasonal mean. Each available sample contributes equally even though calendar intervals differ. Integrating a curve through the gap would introduce assumptions about unobserved conditions; it would not remove the uncertainty.
Four valid rows out of six describes this constructed schedule, not continuous coverage of two-thirds of the season. Missingness can be selective: for example, quality masking can remove some conditions more often than others. The available samples alone cannot establish that the unobserved period behaved similarly.
Before using real satellite time series
Use a consistent area or explicitly track changes in footprint and usable area.
Check dates, ordering and duplicates; preserve the distinction between acquisition dates and composite periods.
Keep scale, units, preprocessing, grid alignment and quality masks consistent or document justified differences.
Keep observations and modelled values in separate fields, with the modelling rule and its limits.
Use independent evidence before interpreting a gap or an estimated curve as planting delay, crop stress or yield change.
Check your understanding
Does a missing date mean NDVI was zero? No. Missing means no usable value is available; a valid observed zero is a separate case.
Why is the largest gap 25 days? The calculation compares successive valid dates: 6 June to 1 July, even though two scheduled rows occur inside that interval.
Does a smooth interpolated curve prove what happened? No. It displays estimates under assumptions. In this example the long gap remains unfilled.
Sources and reuse
Plotting references: Matplotlib’s missing-value line example and date tick locators and formatters, reviewed 28 November 2026. The first explains why retaining masked/NaN positions breaks a line whereas removing them joins the remaining points. The second documents calendar-axis formatting.
All dates and NDVI values here are synthetic. No satellite retrieval, crop identification, biological validation or interpolation accuracy assessment was performed. The original example code and figure are available under the MIT License, copyright 2026 Data Science with DEB.
Return to the learning path. Next we will examine why changing valid area can change a field-level mean even when the underlying measurements do not change.
A GeoTIFF can open normally, contain plausible NDVI values and still place them in a different location. In this lesson, we deliberately move the same raster 100 metres east, inspect it in QGIS and separate a display check from a geographic-accuracy claim.
Start with lesson five’s value and metadata checks. Here you will learn to compare footprints using the same display range. This is an article and code lesson; no new video accompanies it.
What the controlled example proves
We use the archived lesson-five NDVI raster: 72 rows × 63 columns, one float32 band, ten-metre pixels and EPSG:32643 (WGS 84 / UTM zone 43N). All 4,536 samples are valid in this file. The stored mean is approximately 0.467969.
The control changes only the affine transform’s easting origin from 576440 to 576540 metres. The northing origin, CRS, dimensions, values and validity masks stay the same. This is an intentionally incorrect metadata edit, not a reprojection, correction or new satellite observation. Do not use it as a way to repair a misaligned dataset.
Original bounds: (576440, 3418790, 577070, 3419510). Shifted bounds: (576540, 3418790, 577170, 3419510). At zero-based row 36, column 31, the pixel centre moves from (576755, 3419145) to (576855, 3419145). Its NDVI stays approximately 0.628600.
Same numbers on the same coordinate axes
Both panels use fixed grayscale limits 0–1 and the same geographic axes. The dashed orange line marks the original western edge; the dotted green line marks the shifted edge. Negative NDVI values display black under this range but remain unchanged in the files. Select the figure to open it at full size.
Open both rasters in QGIS
Run the complete Python example below in a writable lesson folder. Keep the original and generated control clearly named and separate from your research outputs.
In QGIS, use Layer → Add Layer → Add Raster Layer. Add ndvi.tif and INTENTIONALLY_shifted_100m_east.tif. Put the shifted control above the original in the Layers panel.
Confirm the project CRS is EPSG:32643 for this comparison. Double-click each layer and inspect its Information and Source properties. Compare the declared CRS, extent, dimensions and pixel size with the expected values above. Do not change the CRS label merely to make layers appear aligned.
In each layer’s Symbology, select Singleband gray, Band 1, and the same fixed minimum 0 and maximum 1 with a min/max stretch. Avoid a separate automatic stretch based on each layer or a changing canvas extent. For checking negative values, repeat with a common range that includes them, such as −0.2 to 1.
Zoom to the combined footprints, then leave the canvas extent unchanged. Toggle the shifted control off and on using its checkbox. The repeated pattern moves east. Do not zoom to each layer independently while comparing: recentering each image can conceal the displacement.
Use Identify Features and inspect an appropriate pixel and layer. A click at the same map coordinate in two shifted rasters need not address the same row and column. Compare the stated pixel centres and expected geometry as well as the samples.
The QGIS visual check we performed
On 28 November 2026, QGIS 3.32 loaded the original and reconstructed shifted TIFFs. Both legends showed fixed 0–1 grayscale limits and the project showed EPSG:32643. Toggling the shifted layer at an unchanged canvas extent visibly displaced the repeated pattern east. The matching arrays, masks and exact 100-metre coordinate difference were independently checked by the Python script. The screenshots document the layer toggle; they are not a survey or an independent reference overlay.
Original visible; shifted control unchecked. The original footprint ends farther west. Both layer legends retain the same 0–1 range. Open the screenshot at full size to inspect the interface.Shifted control enabled above the original. The pattern moves east; a western strip of the original remains visible beneath it. The canvas has not been recentered.
Run the complete free example
The input is the same public numerical NDVI TIFF used in lesson five. The script downloads it only when absent, verifies its SHA-256, creates the separate shifted control, compares values and masks, and writes a figure and JSON results. Save the code as lesson06.py. Reruns overwrite its generated outputs; the original input is not overwritten.
"""Lesson 6: controlled metadata error, not a correction or reprojection.
MIT License, Copyright 2026 Data Science with DEB.
Satellite input retains Copernicus source terms.
"""
from pathlib import Path
import hashlib
import json
import urllib.request
import numpy as np
import rasterio
from affine import Affine
from rasterio.plot import plotting_extent
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
folder = Path(__file__).resolve().parent
original = folder / 'ndvi.tif'
url = 'https://dibyendudeb.com/wp-content/uploads/2026/11/lesson-05-ndvi.tif'
expected_hash = '6763cde9ba86259c1b32e6c8188dc0fbe5f48af202eb1b2e7adf2d49f8694a94'
if not original.exists():
urllib.request.urlretrieve(url, original)
assert hashlib.sha256(original.read_bytes()).hexdigest() == expected_hash
with rasterio.open(original) as src:
values = src.read(1)
valid = src.read_masks(1)
profile = src.profile.copy()
expected = src.transform
original_bounds = list(src.bounds)
centre = src.xy(36, 31)
extent_a = plotting_extent(src)
assert src.crs.to_epsg() == 32643
assert values.shape == (72, 63)
assert src.res == (10, 10)
shifted = folder / 'INTENTIONALLY_shifted_100m_east.tif'
# Shift map coordinates, not array indices. Do not use this to repair data.
profile['transform'] = Affine.translation(100, 0) * expected
with rasterio.open(shifted, 'w', **profile) as dst:
dst.write(values, 1)
with rasterio.open(shifted) as src:
assert np.array_equal(src.read(1), values)
assert np.array_equal(src.read_masks(1), valid)
shifted_centre = src.xy(36, 31)
assert shifted_centre[0] - centre[0] == 100
assert shifted_centre[1] == centre[1]
assert src.transform != expected
shifted_bounds = list(src.bounds)
extent_b = plotting_extent(src)
result = dict(crs='EPSG:32643', shape=list(values.shape),
original_bounds=original_bounds, shifted_bounds=shifted_bounds,
original_centre=list(centre), shifted_centre=list(shifted_centre),
pixel_row_col=[36, 31], pixel_value=float(values[36, 31]),
mean=float(values.astype('float64').mean()),
identical_values_and_masks=True, shift_east_metres=100,
source_sha256=expected_hash,
rasterio_version=rasterio.__version__, numpy_version=np.__version__)
(folder / 'placement_verification.json').write_text(json.dumps(result, indent=2))
fig, axes = plt.subplots(2, 1, figsize=(7, 10), constrained_layout=True)
for ax, extent, label in zip(axes, [extent_a, extent_b],
['Original declared grid', 'Controlled error: 100 m east']):
ax.imshow(np.ma.masked_where(valid == 0, values), extent=extent,
cmap='gray', vmin=0, vmax=1, interpolation='nearest')
ax.set_xlim(576390, 577220)
ax.set_ylim(3418740, 3419560)
ax.set_title(label)
ax.set_xlabel('Easting (m), EPSG:32643')
ax.set_ylabel('Northing (m)')
ax.ticklabel_format(useOffset=False, style='plain')
ax.set_xticks([576400, 576800, 577200])
ax.set_yticks([3418800, 3419100, 3419500])
ax.axvline(576440, color='#db6e24', ls='--', lw=1)
ax.axvline(576540, color='#208c7d', ls=':', lw=1)
fig.suptitle('Same values and masks. Different map positions.\nFixed grayscale 0-1; negative values display black.')
fig.savefig(folder / 'placement_comparison.png', dpi=150)
plt.close(fig)
print(json.dumps(result, indent=2))
Executed on Windows with Python 3.14, Rasterio 1.5.0 and NumPy 2.5.1. All listed assertions passed. This combination emitted NumPy shape-setting deprecation warnings from raster reads; those warnings did not invalidate the checks. This small in-memory demonstration is not a large-raster processing design.
Consistency is not absolute position accuracy
Matching the archived source grid establishes consistency with that source. It does not establish that the source itself is correctly positioned on the ground. Both files could share a source error. For a real positional assessment, use independent reference data of suitable quality, date and resolution, account for CRS/datum transformations, and measure residual displacement at identifiable features. No such independent ground-reference overlay was performed here.
Likewise, a different colour palette or contrast stretch does not change stored NDVI. Exporting a rendered RGB image can create colour-channel samples instead of the original measurement. Keep numerical data and styled communication figures separate.
Before sharing your result
Reopen the delivered TIFF and check its expected CRS, transform, bounds, dimensions, resolution, nodata and validity masks.
Compare numerical values and selected pixel centres, not just the mean or a pleasing image.
Use the same display range and unchanged canvas extent when comparing images.
Record what reference was used, what was actually checked and what remains uncertain.
Never distribute an intentionally shifted control as corrected data.
Test your understanding
Can an unchanged mean reveal a transform-only shift? No. Every value can remain identical while their map locations change.
Why keep the same canvas extent during a toggle? Independently recentering each raster can make the same pattern appear stationary even when the footprints differ.
Does a successful QGIS toggle validate crop condition or ground accuracy? No. It illustrates a controlled spatial inconsistency. Those scientific claims require separate evidence.
Contains modified Copernicus Sentinel data 2024, processed through Google Earth Engine. The archived input derives from a Punjab sample dated 13 October 2024; crop identity and condition are unverified. Source data retain applicable Copernicus terms. The example script, original figure and display styles are released under the MIT License, copyright 2026 Data Science with DEB.
You have calculated NDVI, exported a GeoTIFF and made an attractive map. Before sharing it, ask two separate questions: did the file preserve the intended values, and did it preserve their intended locations? A successful export alone answers neither.
This lesson builds on the real-scene comparison in lesson four. It includes an executable inspector and verified examples. No new video accompanies this article.
Check the values and their location
A GeoTIFF can hold numerical bands and geographic referencing. For an affine-georeferenced raster, the CRS identifies the coordinate system and the transform maps pixel positions into it. Changing only a CRS label is not reprojection. Dimensions describe rows, columns and bands; after a deliberate crop or reprojection they may legitimately change. Compare against the intended output, not an assumption that every property must match the input.
For the supplied NDVI example, the expected grid is 72 rows × 63 columns, one band, EPSG:32643, ten-metre cells, and upper-left grid corner (576440, 3419510). Its bounds are (576440, 3418790, 577070, 3419510). The upper-left pixel centre is (576445, 3419505), five metres inward from each edge. These coordinates are metres, not longitude and latitude.
We made a separate, intentionally incorrect copy by shifting the transform 100 metres east while retaining every pixel value and the CRS. It opened normally and its numerical array was identical, but its bounds and transform differed. This is a controlled metadata error, not a new observation or a reprojection. Statistics alone cannot detect it.
Keep missing observations separate from valid zero values
The example uses −9999 as its declared nodata sentinel. A valid NDVI of zero must remain valid. Read with masked=True to use the applicable mask, then separately exclude non-finite values. A nodata value of None does not prove that every pixel is usable: a dataset may have another validity mask.
Rasterio’s GDAL-style mask marks valid cells with nonzero values; a NumPy masked array marks invalid cells with True. These conventions are opposite. If the dataset depends on an external mask or other auxiliary files, include them when sharing and test the actual delivery package. Mask precedence can depend on the available mask sources.
Choose a dtype and interpret scaling explicitly
A directly stored fractional NDVI raster can use float32. Converting fractions directly to an integer dtype can lose their decimal information. Scaled integers can also represent measurements, provided their scale and offset are documented and applied correctly.
The inspector below reads stored samples, removes masked and non-finite values, and explicitly calculates stored × scale + offset from the band metadata. If those metadata are absent or wrong, the script cannot infer the intended product conversion. Do not apply an additional conversion to a raster whose values are already in the target units.
Inspect the distribution without treating it as proof
Check minimum, maximum, mean and valid finite count. For NDVI made from non-negative red and NIR reflectance with a positive denominator, the algebra gives a range from −1 to +1. Investigate unexpected values rather than silently clipping them. The physical assumptions, preprocessing and quantity matter. A plausible distribution still cannot establish crop condition, scientific accuracy or correct geographic placement.
Same values, different colours
Both panels use the same NDVI array and limits −0.2 to 1.0. Only the display palette changes.
Changing display symbology does not require changing the numerical raster. Exporting a rendered RGB map is different: its colour-channel samples may no longer contain the original NDVI measurements. Share numerical outputs for analysis and a separate styled figure for communication. Check the export options of the software you use. No GIS menu or overlay workflow has been tested in this lesson.
Run the read-only inspector
Download the numerical NDVI example. Save the script below as inspect_geotiff.py. It reads the file without modifying it. It loads one band at a time into memory, so large rasters require a block-wise approach.
import rasterio
import numpy as np
import sys
file_path = sys.argv[1]
with rasterio.open(file_path) as src:
print("----- SPATIAL INFORMATION -----")
print("CRS:", src.crs)
print("Transform:", src.transform)
print("Bounds:", src.bounds)
print("Resolution:", src.res)
print("\n----- RASTER STRUCTURE -----")
print("Width:", src.width)
print("Height:", src.height)
print("Bands:", src.count)
print("Data types:", src.dtypes)
print("Nodata values:", src.nodatavals)
print("Scale factors:", src.scales)
print("Offsets:", src.offsets)
print("\n----- PIXEL INFORMATION -----")
for band in range(1, src.count + 1):
data = src.read(band, masked=True)
raw = data.compressed()
# Exclude non-finite stored values
raw = raw[np.isfinite(raw)]
# Interpret scale and offset
values = (
raw.astype("float64")
* src.scales[band - 1]
+ src.offsets[band - 1]
)
values = values[np.isfinite(values)]
print("\nBand:", band)
print("Total pixels:", data.size)
print("Valid finite pixels:", values.size)
print(
"Excluded pixels:",
data.size - values.size
)
if values.size > 0:
print("Minimum:", values.min())
print("Maximum:", values.max())
print("Mean:", values.mean())
print("Std. deviation:", values.std())
else:
print("No valid finite pixels found.")
What was actually tested
The inspector ran with Rasterio 1.4.4 and NumPy 2.3.5 on these constructed cases:
Case
Valid finite cells
Interpreted mean
Float with −9999 nodata
3 of 4
0.5
Integer, scale 0.0001, offset −0.1
4 of 4
0.05
Explicit mask, no nodata sentinel
3 of 4
0.5
Unmasked NaN
3 of 4
0.5
All cells nodata
0 of 4
No mean reported
All expected counts and means passed. On the real-scene NDVI output, it reported 4,536 valid finite cells and a mean approximately 0.467969. Metadata checks matched the intended grid. This is archived Sentinel-2-derived data from Punjab, dated 13 October 2024; crop identity and condition remain unverified.
Reopen, compare, then inspect against a reference
Close the writer and reopen the actual saved file. Compare its CRS, transform, shape, dtype, nodata, mask and values with the intended result, using tolerances suitable for floating-point storage. The inspector reports properties; it does not automatically know your expected answer.
Then inspect the raster against a trusted geographic reference in a GIS. Matching metadata proves consistency with the declared grid, not absolute geolocation accuracy. That independent GIS overlay remains a recommended next check, not an action performed here.
Learner checklist
The delivered file reopens successfully, with any required auxiliary files.
CRS, transform, bounds, resolution, dimensions and band count match the intended output.
Dtype preserves the required precision; scale and offset are correctly interpreted.
Applicable masks and non-finite values are handled; valid zeros remain valid.
Reopened pixel values match the intended calculation within stated tolerances.
The spatial position is checked against a trusted reference.
Numerical data and rendered colour images are clearly distinguished.
Provenance, units, limitations and reuse terms accompany the output.
Test your understanding
1. Correct NDVI values, wrong location: what should you check first? CRS and transform, then compare the footprint against the intended grid and a trusted reference.
2. Which dtype can directly store fractional NDVI? Float32 is a practical choice, subject to its precision. Integers require an intentional encoding scheme.
3. Does changing only a display palette change stored NDVI? No. A separately exported rendered image may instead store colour-channel values, so distinguish the two products.
Contains modified Copernicus Sentinel data 2024, processed through Google Earth Engine. Source data retain Copernicus terms. The lesson inspector, constructed tests and original figure are released under the MIT License, copyright 2026 Data Science with DEB.
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.
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.
Shared display range −0.2 to 1.0. Four EVI cells exceed the upper colour limit; their numerical values remain unchanged in the outputs.
Index
Valid pixels
Mean
Minimum
Maximum
NDVI
4,536
0.467969
−0.160850
0.846559
SAVI
4,536
0.274651
−0.083290
0.605836
EVI
4,536
0.287490
−0.084590
1.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.
Horizontal axes show correctly scaled values. Vertical axes intentionally omit scaling. Black lines mark equality; the EVI panel retains extreme diagnostic values.
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.
"""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.
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.
Synthetic reflectances and class labels. Grey cells in the right panel are missing, not zero-valued observations.
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.
"""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.
Two arrays can both contain six rows and six columns, use the same coordinate reference system and have ten-metre cells—yet refer to different locations. Pixel-wise arithmetic matches array positions. It does not check where those positions lie on the ground.
This lesson isolates that problem with a synthetic example. You will inspect the grid, align one raster to a reference, preserve missing coverage and verify the saved result. No satellite download or account is needed.
Both grids contain 6 × 6 cells in EPSG:32646. Their upper-left origins are (500000, 3000000) and (500010, 3000000). The second footprint begins one cell farther east. Both sample the same linear reflectance surface at their own cell centres. One source cell is deliberately missing.
Synthetic geometry: matching dimensions and resolution do not establish matching cell locations.
Subtracting the arrays directly produces an apparent difference of approximately 0.04 at the 35 valid source-array positions. This difference is constructed by the spatial gradient and grid offset; it is not evidence of crop change. After alignment, compare only cells valid in both arrays.
What to inspect before combining bands
Check
Question to answer
CRS
Are coordinates expressed in compatible systems?
Affine transform
Do origins, cell spacing and orientation describe the same grid?
Width and height
Do the destination dimensions match the chosen reference?
Bounds and coverage
Which reference cells actually have source observations?
Nodata and masks
Which cells must remain excluded?
For affine-georeferenced rasters, matching the CRS, transform and dimensions establishes the same pixel grid. Bounds and resolution provide useful diagnostics. Choosing a reference is an analysis decision: consider the bands, their native resolution, required footprint and intended comparison.
Run the complete free example
The full source is included below. Save it as alignment_demo.py in a writable folder. Install the package versions used for the original verification, then run the script. Python 3.11 or later is required; package availability also depends on your platform.
The script generates its own teaching data. It writes four GeoTIFFs, two figures and verification.json into an outputs folder beside the script. Files with those names are overwritten on reruns.
"""Synthetic raster alignment lesson. Run with Python 3.11+ from any folder."""
from pathlib import Path
import json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import rasterio
from rasterio.transform import from_origin, array_bounds
from rasterio.warp import reproject, Resampling
OUT = Path(__file__).resolve().parent / 'outputs'
OUT.mkdir(exist_ok=True)
CRS = 'EPSG:32646'
NODATA = -9999.0
shape = (6, 6)
reference = from_origin(500000, 3000000, 10, 10)
shifted = from_origin(500010, 3000000, 10, 10)
# Both rasters sample the SAME continuous synthetic surface at their own centres.
rows, cols = np.indices(shape)
def surface(transform):
x = transform.c + (cols + .5) * transform.a
y = transform.f + (rows + .5) * transform.e
return (.2 + .004 * (x - 500000) + .001 * (3000000 - y)).astype('float32')
first, second = surface(reference), surface(shifted)
# One missing source cell tests nodata propagation independently of the edge.
second[2, 2] = NODATA
def write(name, data, transform, nodata):
with rasterio.open(OUT / name, 'w', driver='GTiff', height=6, width=6,
count=1, dtype=data.dtype, crs=CRS, transform=transform,
nodata=nodata) as dst:
dst.write(data, 1)
write('reference.tif', first, reference, NODATA)
write('shifted.tif', second, shifted, NODATA)
aligned = np.full(shape, NODATA, dtype='float32')
# Bilinear suits this continuous linear teaching surface. Keep the reference grid.
reproject(source=second, destination=aligned, src_transform=shifted,
src_crs=CRS, dst_transform=reference, dst_crs=CRS,
src_nodata=NODATA, dst_nodata=NODATA,
resampling=Resampling.bilinear)
write('aligned.tif', aligned, reference, NODATA)
valid_naive = second != NODATA
valid_aligned = aligned != NODATA
naive_difference = np.where(valid_naive, second - first, np.nan)
aligned_difference = np.where(valid_aligned, aligned - first, np.nan)
# Categorical mask uses nearest-neighbour, with 255 reserved for missing coverage.
classes = np.where(cols < 3, 1, 2).astype('uint8')
classes[2, 2] = 255
aligned_classes = np.full(shape, 255, dtype='uint8')
reproject(source=classes, destination=aligned_classes, src_transform=shifted,
src_crs=CRS, dst_transform=reference, dst_crs=CRS,
src_nodata=255, dst_nodata=255, resampling=Resampling.nearest)
write('classes_aligned.tif', aligned_classes, reference, 255)
assert np.allclose(naive_difference[valid_naive], .04, atol=1e-6)
assert np.max(np.abs(aligned_difference[valid_aligned])) < 1e-6
assert np.all(aligned[:, 0] == NODATA)
assert aligned[2, 3] == NODATA
assert set(np.unique(aligned_classes)) <= {1, 2, 255}
assert np.all(aligned_classes[:, 0] == 255)
assert aligned_classes[2, 3] == 255
with rasterio.open(OUT / 'aligned.tif') as dst:
assert dst.crs == rasterio.crs.CRS.from_string(CRS)
assert dst.transform == reference and dst.shape == shape
assert dst.dtypes == ('float32',) and dst.nodata == NODATA
assert np.array_equal(dst.read(1), aligned)
plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 12})
fig, axes = plt.subplots(1, 2, figsize=(12, 5), constrained_layout=True)
for transform, color, label in [(reference, '#205d49', 'Reference grid'),
(shifted, '#b45121', 'Shifted grid')]:
xmin, ymin, xmax, ymax = array_bounds(6, 6, transform)
# Local coordinates preserve exact offset while keeping labels readable.
for x in np.arange(xmin, xmax + 1, 10):
axes[0].plot([x-500000]*2, [ymin-2999940,ymax-2999940], color=color, alpha=.65)
for y in np.arange(ymin, ymax + 1, 10):
axes[0].plot([xmin-500000,xmax-500000], [y-2999940]*2, color=color, alpha=.65)
axes[1].plot([], [], color=color, label=label)
axes[0].set(title='Equal shapes, offset footprints', xlabel='Easting relative to 500000 m', ylabel='Northing relative to 2999940 m', aspect='equal')
axes[0].annotate('10 m shift', xy=(10,65), xytext=(0,65), arrowprops={'arrowstyle':'<->'})
axes[0].set_ylim(-3,73)
axes[1].axis('off')
axes[1].text(0,.88,'Both arrays are 6 × 6', fontsize=20, weight='bold', transform=axes[1].transAxes)
axes[1].text(0,.68,'Same CRS and 10 m resolution\nDifferent affine origins\nColumn 0 refers to different ground cells', linespacing=1.8, transform=axes[1].transAxes)
axes[1].text(0,.26,'Choose a common grid before\npixel-wise calculations.', fontsize=18, color='#205d49', transform=axes[1].transAxes)
axes[1].legend(loc='lower left', frameon=False)
fig.suptitle('Synthetic example • Data Science with DEB', fontsize=16)
fig.savefig(OUT / '01_grid_offset.png', dpi=180)
plt.close(fig)
fig, axes = plt.subplots(1,2, figsize=(12,5), constrained_layout=True)
for ax, values, title in zip(axes,[naive_difference,aligned_difference],['Naive array subtraction','After alignment to reference']):
im=ax.imshow(values, cmap='RdBu_r', vmin=-.05,vmax=.05)
ax.set(title=title,xlabel='Reference column',ylabel='Reference row')
for r in range(6):
for c in range(6):
ax.text(c,r,'Missing' if np.isnan(values[r,c]) else f'{values[r,c]:.2f}',ha='center',va='center',fontsize=9)
fig.colorbar(im,ax=axes,label='Difference in synthetic reflectance',shrink=.85)
fig.suptitle('Same underlying surface • apparent difference comes from grid offset',fontsize=14)
fig.savefig(OUT / '02_difference_comparison.png', dpi=180)
plt.close(fig)
report={'synthetic':True,'rasterio_version':rasterio.__version__,
'shape':[6,6],'crs':CRS,'offset_metres':10,
'naive_mean_absolute_difference':float(np.nanmean(abs(naive_difference))),
'aligned_max_absolute_difference':float(np.nanmax(abs(aligned_difference))),
'aligned_valid_pixels':int(valid_aligned.sum()),'aligned_missing_pixels':int((~valid_aligned).sum()),
'categorical_output_values':[int(x) for x in np.unique(aligned_classes)],
'checks':'PASS'}
(OUT/'verification.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
Check your result
The same constructed surface before and after alignment. Both panels use the same colour range. Missing cells are excluded.
Expect 29 valid aligned cells and seven missing cells: six along the uncovered western edge and one internal source gap. The categorical output contains labels 1 and 2, with 255 reserved for missing data. The script checks the output grid, dtype, nodata value and values after reopening the GeoTIFF.
Continuous values and category labels need different treatment
The demonstration explicitly uses bilinear resampling for its continuous linear surface. For category labels it uses nearest neighbour, preventing interpolated category numbers. The right continuous-data method depends on the quantity, scale change and analysis; this example is not a universal resampling prescription.
What this does—and does not—prove
The exact zero difference follows from this controlled linear surface and whole-cell shift. Real scenes may retain differences after alignment. Different spectral bands measure different responses, and different dates can contain real changes. Alignment makes cell locations comparable; it does not make their measurements identical.
Resampling to smaller cells does not recover new spatial detail. Missing coverage must not become a zero-valued observation. For vegetation indices, also verify product-specific scaling and offsets, cloud and shadow quality, and valid denominators before calculation.
Try this before the next lesson
Inspect reference.tif, shifted.tif and aligned.tif in your GIS. Explain why the western edge remains missing. Then locate the internal missing source cell and its destination position. A successful check should explain the gaps, rather than merely produce a complete-looking map.
Next lesson: clouds, shadows and missing observations—how quality masks change which pixels can support an index calculation.
Sources and reuse
Implementation references: Rasterio reprojection and Rasterio resampling. The demonstration was originally executed with Rasterio 1.4.4; its saved verification is reproduced above.
Code, synthetic rasters and original figures are supplied under the MIT License. Third-party software retains its own license.
MIT License
Copyright (c) 2026 Data Science with DEB
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The video uses the stock synthetic Kokoro bm_george narration voice. These are educational synthetic data, with no claim about a particular field or crop.
We expanded our satellite crop-monitoring prototype’s historical test to five seasons. The initial planting rule raised an alert in every season, prompting us to reconsider how it identifies unusual conditions.
Our next experiment will examine more consistent satellite observations and crop-specific areas. Independent planting records are still needed to assess accuracy.
We built a prototype that uses radar satellite observations to flag possible planting delays. In a historical replay, the prototype reproduced a flag using imagery acquired by the planting cutoff. We still need independent planting records to check whether that flag corresponded to a delay.
Our next test is to run the same rule on a season with documented normal planting and see whether it raises a false alarm.
While optical satellite sensors (NDVI) suffer an 80–90% cloud-blindspot during the South Asian monsoon, active C-band Synthetic Aperture Radar (Sentinel-1 SAR) penetrates rainclouds to deliver guaranteed 6–12 day crop intelligence. This case study benchmarks the radar pipeline against two historical extremes in Assam: the catastrophic 2022 Kopili river flood in Nagaon and the 2024 Subansiri flash flood in Lakhimpur.
In our previous article, we explored the microwave physics of why optical satellite data fails during overcast seasons. But how does this radar pipeline actually perform against recorded climate disasters on the ground?
To test this empirically, we deployed a multi-season Sentinel-1 dual-orbit radar pipeline across two of the most flood-vulnerable agricultural corridors in Assam: the Nagaon Agricultural Basin (2022) and the Lakhimpur Central Paddy Belt (2024). The empirical data reveals clear, objective microwave scattering signatures that track field submergence, plant survival, and post-flood vegetative recovery.
1. Detection Framework: Dual-Orbit SAR & Cropland Masking
A major challenge in satellite analytics is spatial aggregation bias: averaging raw radar backscatter across a broad district polygon inadvertently mixes settlements, tree canopies, and tea estates with rice paddies, artificially inflating backscatter values. To eliminate this noise, our workflow enforces two critical constraints:
ESA WorldCover 10m Cropland Masking: Pixel filtering isolates strictly Class 40 (Cropland), ensuring radar statistics represent active agricultural fields only.
Dual-Orbit Fusion: Combining ascending (evening) and descending (morning) passes provides high-frequency observations (every 6 to 12 days), closing mid-monsoon data gaps.
Physical Metrics Tracked: Co-polarization (σ0VV) for surface specular water reflection, cross-polarization (σ0VH) for canopy volume scattering, and the standardized biomass anomaly (ZSAR) against a 4-year rolling baseline.
2. Empirical Case Studies: Ground-Truth Disaster Verification
The dual-panel trajectory plot below demonstrates the empirical radar response across both historical extreme events:
In late June and early July 2022, the Kopili river basin experienced catastrophic embankment breaches, submerging thousands of hectares of Sali rice seedlings. Conventional ground assessment teams were unable to enter flooded villages for weeks.
Radar Detection: On July 5, 2022, Sentinel-1 registered an acute plunge in cropland σ0VH backscatter to −20.0 dB, directly crossing the calibrated submergence alarm threshold. The specular reflection of standing floodwaters completely extinguished canopy volume scattering.
Recovery Dynamics: Once floodwaters receded in late July, farmers initiated secondary transplanting. Backscatter curves rebounded rapidly across August and September, supported by alluvial silt deposition, with final reproductive biomass closing at +0.02 σ (fully normalized against the 4-year baseline).
Case 2: Lakhimpur Central Belt (Kharif 2024) — Flash Inundation vs. Harvest Normalcy
In early July 2024, rapid flash flooding across the Subansiri river floodplain raised immediate alarms regarding total seasonal crop loss across northern Assam.
Radar Detection: On July 4, 2024, our pipeline captured a sharp plunge in σ0VH down to −20.5 dB. However, consecutive overpasses proved that floodwaters receded rapidly within 10 days, with backscatter rebounding to −17.8 dB by late July.
Agronomic Takeaway: Because submergence was transient (<12 days), mature vegetative tillering resumed unhindered. By November 2024, final biomass closed at +0.05 σ above baseline. Continuous SAR tracking successfully separated transient flood stress from permanent crop mortality.
3. Multi-Season Quantitative Comparison
Evaluation Parameter
Nagaon Basin (Kharif 2022)
Lakhimpur Belt (Kharif 2024)
Target Crop & Mask
Kharif Sali Rice • ESA 10m Cropland
Kharif Sali Rice • ESA 10m Cropland
Peak Inundation Backscatter
−20.0 dB (July 5, 2022)
−20.5 dB (July 4, 2024)
Submergence Duration
Sustained Flood (≥ 2 Overpasses)
Transient Flash Flood (1 Overpass)
Late-Season Biomass Anomaly (ZSAR)
+0.02 σ (Post-flood recovery)
+0.05 σ (Full maturity normal)
Analytical Classification
Severe Inundation / Sowing Delay Shock
Transient Inundation / Resilient Recovery
4. Reproducible Earth Engine Pipeline Snippet
To extract dual-orbit Sentinel-1 backscatter masked to ESA WorldCover cropland in Python:
import ee
import pandas as pd
ee.Initialize(project='your-cloud-project-id')
# 1. Define Cropland Mask (Class 40)
worldcover = ee.ImageCollection("ESA/WorldCover/v100").first()
cropland_mask = worldcover.select('Map').eq(40)
# 2. Query Sentinel-1 GRD Collection across both orbits
s1 = (ee.ImageCollection('COPERNICUS/S1_GRD')
.filterBounds(aoi_geometry)
.filterDate('2024-06-01', '2024-11-15')
.filter(ee.Filter.eq('instrumentMode', 'IW'))
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV'))
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')))
def extract_cropland_stats(img):
masked = img.updateMask(cropland_mask)
vv = masked.select('VV').focal_mean(1.5, 'circle', 'pixels')
vh = masked.select('VH').focal_mean(1.5, 'circle', 'pixels')
stats = ee.Image([vv, vh]).reduceRegion(
reducer=ee.Reducer.mean(),
geometry=aoi_geometry,
scale=30,
maxPixels=1e9
)
return ee.Feature(None, {
'date': img.date().format('YYYY-MM-dd'),
'VV': stats.get('VV'),
'VH': stats.get('VH')
})
raw_data = s1.map(extract_cropland_stats).getInfo()['features']
df = pd.DataFrame([f['properties'] for f in raw_data if f['properties']['VV'] is not None])
print(f"Ingested {len(df)} cloud-free cropland observations.")
Research Collaboration & Data Inquiries:
Are you analyzing crop damage, remote sensing hydrology, or spatial flood modeling across Eastern India? For collaborative research discussions, code exchanges, or regional dataset queries, feel free to reach out directly via the contact page or at contact@dibyendudeb.com.