Reading Sentinel-2 into pyramids¶
pyramids-eo reads a Sentinel-2 product straight into a normal
pyramids.Dataset through GDAL's bundled SENTINEL2 driver — no
sentinelsat, rasterio, or SNAP. GDAL parses the .SAFE product structure, pyramids does the raster work, and
pyramids_eo.sentinel adds the instrument semantics: which subdataset is which band, DN → reflectance, and
scene-classification masking. Every call returns a plain pyramids Dataset, so crop, to_crs, plot, and
to_file all work on the result.
This notebook teaches the public entry points in pyramids_eo.sentinel:
| Function | What it gives you |
|---|---|
open_product(path) |
a typed S2Product describing the scene |
from_sentinel2(path, bands=..., ...) |
selected bands → a single Dataset |
from_sentinel2(..., reflectance=True) |
DN read back as surface reflectance |
from_sentinel2(..., mask_scl=[...]) |
scene-classification masking |
By the end you'll read a true-colour composite, control bands and resolution, harmonise bands that live on different grids, and mask clouds with the scene-classification band.
Prerequisite — a granule and credentials. We read a real Level-2A scene in place off the Copernicus Data Space Ecosystem (CDSE)
eodataS3 store — only the band windows we ask for are fetched, so there is no multi-GB download. That needs CDSE S3 keys in your environment:CDSE_S3_ACCESS_KEYandCDSE_S3_SECRET_KEY(create them at the CDSE S3 keys manager). To read a.SAFEyou have downloaded locally instead, just pointPRODUCTat its folder or.zipand skip the S3 setup.
Setup¶
Imports, and one helper that points GDAL's /vsis3 reader at CDSE's eodata store using the keys from your
environment. (Reading a local .SAFE/.zip needs none of this.)
%matplotlib inline
import os
import warnings
import numpy as np
import pyramids # noqa: F401 (activates the bundled GDAL/osgeo)
from osgeo import gdal
# Two benign internal warnings would otherwise clutter the output below.
warnings.filterwarnings("ignore", message="Warning: 'partition' will ignore")
warnings.filterwarnings("ignore", message="The no_data_value -9999 is out of range")
from pyramids_eo.sentinel import from_sentinel2, open_product
from pyramids_eo.sentinel.s2.masks import SclClass
def configure_cdse_s3():
# Point GDAL's /vsis3 reader at CDSE eodata using the CDSE_S3_* env keys.
for key, value in {
"AWS_S3_ENDPOINT": "eodata.dataspace.copernicus.eu",
"AWS_ACCESS_KEY_ID": os.environ.get("CDSE_S3_ACCESS_KEY", ""),
"AWS_SECRET_ACCESS_KEY": os.environ.get("CDSE_S3_SECRET_KEY", ""),
"AWS_VIRTUAL_HOSTING": "FALSE",
"AWS_HTTPS": "YES",
"GDAL_DISABLE_READDIR_ON_OPEN": "EMPTY_DIR",
}.items():
gdal.SetConfigOption(key, value)
configure_cdse_s3()
Our scene is a cloud-free Level-2A tile over Madrid (20 Aug 2024, tile T30TVK). PRODUCT is the path GDAL
opens — the product's MTD_MSIL2A.xml inside the .SAFE, here on CDSE's S3 store. AOI is a small ~3 km window in
the tile's native UTM CRS (EPSG:32630); keeping the read window small keeps every cell fast.
PRODUCT = (
"/vsis3/eodata/Sentinel-2/MSI/L2A/2024/08/20/"
"S2A_MSIL2A_20240820T105621_N0511_R094_T30TVK_20240820T152852.SAFE/MTD_MSIL2A.xml"
)
AOI = (440000, 4470000, 443000, 4473000) # (minx, miny, maxx, maxy) in EPSG:32630
The product model¶
open_product sniffs the driver and returns a typed S2Product — the level, the DN → reflectance quantification
value, the native resolutions present (10 / 20 / 60 m), the UTM zone, and the band catalogue. Nothing is read yet;
this is just the manifest.
product = open_product(PRODUCT)
print("level: ", product.level)
print("quantification:", product.quantification)
print("resolutions: ", product.resolutions, "m")
print("UTM EPSG: ", product.epsg_codes)
print("baseline: ", product.baseline)
sorted(product.available_bands)
level: L2A quantification: 10000.0 resolutions: [10, 20, 60] m UTM EPSG: [32630] baseline: 05.11
['AOT', 'B1', 'B11', 'B12', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B8A', 'B9', 'CLD', 'SCL', 'SNW', 'WVP']
True-colour reflectance¶
from_sentinel2 selects bands by name and returns a Dataset. With reflectance=True (the default), the DN →
reflectance conversion is recorded as lazy GDAL scale/offset tags rather than a materialised float array — the
values become reflectance only when you read with read_array(), and the tags survive crop/reproject.
Here: red/green/blue (B04/B03/B02, all 10 m) over the AOI, rendered with the Dataset's built-in
percentile-stretched RGB plot.
rgb = from_sentinel2(PRODUCT, bands=["B04", "B03", "B02"], bbox=AOI)
print("shape:", rgb.shape, "| epsg:", rgb.epsg, "| cell:", rgb.cell_size, "m")
rgb.plot(
rgb_options={"rgb": [0, 1, 2], "percentile": 2},
title="Sentinel-2 true colour (B04/B03/B02)",
)
shape: (3, 300, 300) | epsg: 32630 | cell: 10.0 m
<cleopatra.glyphs.gridded.array_glyph.ArrayGlyph at 0x239578517f0>
The scale/offset tags are what make a scaled read return physical reflectance. This is a baseline-≥04.00 product,
so it carries the −1000 radiometric offset: reflectance = (DN − 1000) / 10000. Read both ways to see it:
print("scale :", rgb.scale)
print("offset:", rgb.offset)
scaled = np.asarray(rgb.read_array(), dtype="float64")
print(
"reflectance min / mean / max:",
round(float(np.nanmin(scaled)), 3),
round(float(np.nanmean(scaled)), 3),
round(float(np.nanmax(scaled)), 3),
)
scale : [0.0001, 0.0001, 0.0001] offset: [-0.1, -0.1, -0.1] reflectance min / mean / max: 0.009 0.136 0.691
A single band with a colour map¶
Any band works the same way. The near-infrared B08 (10 m) is high over vegetation and low over built-up land and water — the basis of indices like NDVI.
nir = from_sentinel2(PRODUCT, bands=["B08"], bbox=AOI)
nir.plot(band=0, title="Sentinel-2 near-infrared (B08) reflectance", cmap="RdYlGn")
<cleopatra.glyphs.gridded.array_glyph.ArrayGlyph at 0x23959caf4d0>
Cross-resolution harmonise¶
Sentinel-2 bands live on different grids: B04 is 10 m, the SWIR B11 is 20 m. Ask for both and from_sentinel2
reads each at its native resolution and harmonises them onto the finest grid — here 10 m — so they stack into one
aligned Dataset you can index band-by-band.
stack = from_sentinel2(PRODUCT, bands=["B04", "B11"], bbox=AOI)
print("bands:", stack.band_count, "| cell:", stack.cell_size, "m | shape:", stack.shape)
stack.plot(band=1, title="SWIR B11 (20 m) resampled onto the 10 m grid", cmap="magma")
bands: 2 | cell: 10.0 m | shape: (2, 300, 300)
<cleopatra.glyphs.gridded.array_glyph.ArrayGlyph at 0x2395b033890>
Scene-classification masking¶
Level-2A ships a Scene Classification (SCL) band that labels every pixel — vegetation, water, bare soil, cloud,
cloud shadow, snow. SclClass names those codes. Read the SCL band and plot the classification map:
scl = from_sentinel2(PRODUCT, bands=["SCL"], bbox=AOI)
codes = np.asarray(scl.read_array())
present = sorted(int(c) for c in np.unique(codes))
print("SCL classes present:", [SclClass(c).name for c in present])
scl.plot(band=0, title="Scene classification (SCL codes)", cmap="tab20")
SCL classes present: ['DARK_FEATURE_SHADOW', 'VEGETATION', 'BARE_SOIL_DESERT', 'WATER']
<cleopatra.glyphs.gridded.array_glyph.ArrayGlyph at 0x2395b0cd0f0>
Pass mask_scl= to from_sentinel2 and the listed classes are set to no-data across every band. In practice you
would usually mask the cloud and cloud-shadow classes, but this scene is cloud-free — so to make the effect obvious we
mask everything that isn't vegetation (bare soil, water, and shadow), leaving a vegetation-only view of the
near-infrared band:
non_vegetation = [
SclClass.BARE_SOIL_DESERT,
SclClass.WATER,
SclClass.DARK_FEATURE_SHADOW,
]
masked = from_sentinel2(PRODUCT, bands=["B08"], bbox=AOI, mask_scl=non_vegetation)
nodata = masked.no_data_value[0]
changed = int(np.count_nonzero(np.asarray(masked.read_array()) == nodata))
print(f"pixels masked to no-data ({nodata}):", changed)
masked.plot(
band=0, title="B08 with non-vegetation SCL classes masked out", cmap="RdYlGn"
)
pixels masked to no-data (0.0): 79192
<cleopatra.glyphs.gridded.array_glyph.ArrayGlyph at 0x2395b0cce90>
Takeaway¶
You can now read Sentinel-2 into pyramids with:
open_product(path)for the typedS2Productmanifest;from_sentinel2(path, bands=..., bbox=..., reflectance=True)for an aligned, reflectance-taggedDataset;- band names that harmonise across the 10 / 20 / 60 m grids automatically;
mask_scl=[SclClass...]for scene-classification masking.
Everything returns a standard pyramids Dataset, so from here you'd continue with to_crs, crop, to_file
(GeoTIFF/COG), and the rest of pyramids. For a time series, collection_from_sentinel2([...], root_dir=...) writes
one GeoTIFF per scene and hands back a DatasetCollection.