Lesson 2 · Practical satellite-data analysis
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.
New to vegetation indices? Start with lesson one: NDVI, SAVI and EVI in Python. This lesson explains a spatial check to perform before combining bands.
The example: a ten-metre shift
Page contents
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.

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.
python -m pip install rasterio==1.4.4 numpy==2.3.5 matplotlib==3.10.8
python alignment_demo.py
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

{
"synthetic": true,
"rasterio_version": "1.4.4",
"shape": [
6,
6
],
"crs": "EPSG:32646",
"offset_metres": 10,
"naive_mean_absolute_difference": 0.03999999538064003,
"aligned_max_absolute_difference": 0.0,
"aligned_valid_pixels": 29,
"aligned_missing_pixels": 7,
"categorical_output_values": [
1,
2,
255
],
"checks": "PASS"
}
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.
Continue to lesson three: Clouds, shadows and missing pixels: before you trust an NDVI mean. Follow the validity mask, run the Python example and see why excluded pixels must not become zero-valued observations.