import sys, subprocessIN_COLAB = "google.colab" in sys.modulesif IN_COLAB: subprocess.run([sys.executable, "-m", "pip", "install", "-q", "rasterio", "pystac-client", "planetary-computer", "contextily"], check=True) print("✓ Packages installed")else: print("Running locally - make sure the packages listed above are installed in this environment")Day 1, Session 3: Python for Geospatial Data
EO AI/ML Training · Hands-on notebook
Learning objectives
By the end of this notebook you will be able to:
- Set up a Python geospatial environment (Google Colab or local Jupyter)
- Load, inspect and map vector data with GeoPandas
- Search a STAC catalogue and stream Sentinel-2 Cloud-Optimized GeoTIFFs with pystac-client and Rasterio
- Convert Sentinel-2 L2A digital numbers to surface reflectance (including the processing-baseline offset)
- Calculate NDVI and NDWI and interpret them
- Combine vector and raster data: reprojection, clipping, zonal statistics
- Save results in standard formats (GeoTIFF, GeoPackage)
What you’ll need
| Runtime | Google Colab (CPU is enough) or local Jupyter with Python ≥ 3.10 |
| Accounts | None (a Google account only if you use Colab / Google Drive) |
| Data | Downloaded on the fly: Natural Earth admin boundaries (~15 MB) and a 10 × 10 km Sentinel-2 L2A subset from Microsoft Planetary Computer (no key needed) |
| Time | ~2 hours including the two exercises |
Structure
| Part | Topic | Time |
|---|---|---|
| 1 | Environment setup | 10 min |
| 2 | Python quick recap | 10 min |
| 3 | GeoPandas: vector data | 35 min |
| 4 | Rasterio: Sentinel-2 raster data | 45 min |
| 5 | Combining vector and raster | 20 min |
| 6 | Best practices, recap | 10 min |
—## Part 1: Environment Setup### 1.1 Install packagesColab already ships NumPy, pandas, Matplotlib and GeoPandas; we add Rasterio, the STAC client, the Planetary Computer signing helper and contextily (basemaps). Locally, install the same packages once withpip install geopandas rasterio pystac-client planetary-computer contextily matplotlib.
1.3 Import libraries
import warningsimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.patches import Patchimport geopandas as gpdimport rasteriofrom rasterio.windows import Windowfrom rasterio.warp import transform as warp_transformfrom rasterio.mask import mask as rasterio_maskfrom rasterio.features import geometry_maskfrom rasterio.plot import plotting_extentfrom shapely.geometry import Point, boxwarnings.filterwarnings("ignore", category=RuntimeWarning) # e.g. NaN in divisionsnp.random.seed(42)plt.rcParams["figure.figsize"] = (10, 8)plt.rcParams["figure.dpi"] = 100print("Library versions:")for name, mod in [("NumPy", np), ("pandas", pd), ("GeoPandas", gpd), ("Rasterio", rasterio)]: print(f" {name:<10} {mod.__version__}")—## Part 2: Python Quick RecapIf you are comfortable with Python, skim this part. Everything later builds on these three ideas: data structures, control flow and functions.### 2.1 Data types and structures
# Strings and numbersprovince_name = "Palawan"area_km2 = 14649.7 # float# Lists: ordered, changeableisland_groups = ["Luzon", "Visayas", "Mindanao"]s2_bands_10m = ["B02", "B03", "B04", "B08"] # Sentinel-2 10 m bands# Dictionaries: key -> valueprovince = {"name": "Palawan", "capital": "Puerto Princesa", "lon": 118.74, "lat": 9.74}print(f"Province: {province_name} ({area_km2:,.0f} km²)")print(f"First island group: {island_groups[0]}")print(f"Capital: {province['capital']} at ({province['lon']}, {province['lat']})")2.2 Loops and conditionals
for group in island_groups: print(f" • {group}")ndvi_value = 0.65if ndvi_value < 0: label = "Water"elif ndvi_value < 0.2: label = "Bare soil / built-up / sparse vegetation"elif ndvi_value < 0.5: label = "Moderate vegetation"else: label = "Dense vegetation"print(f"\nNDVI = {ndvi_value} → {label}")# List comprehensionband_labels = [f"Band_{b}" for b in s2_bands_10m]print(band_labels)2.3 FunctionsWe define the NDVI function once and reuse it on real data in Part 4:\[NDVI = \frac{NIR - Red}{NIR + Red}\]
def calculate_ndvi(nir, red): """Normalized Difference Vegetation Index from reflectance arrays. Pixels where NIR + Red == 0 or either input is NaN return NaN. """ nir = np.asarray(nir, dtype="float32") red = np.asarray(red, dtype="float32") denom = nir + red with np.errstate(divide="ignore", invalid="ignore"): ndvi = np.where(denom != 0, (nir - red) / denom, np.nan) return ndvi# Quick test with reflectance values (0-1)print(calculate_ndvi([0.50, 0.30, 0.10], [0.15, 0.12, 0.09]).round(3))# Expected: [0.538 0.429 0.053]—## Part 3: GeoPandas for Vector DataGeoPandas = pandas + a geometry column. It reads and writes Shapefile, GeoJSON, GeoPackage, etc., handles coordinate reference systems (CRS) and performs spatial operations (buffer, intersection, dissolve…).### 3.1 Load Philippine administrative boundariesWe use Natural Earth admin-1 boundaries (public domain) because they download quickly and need no account.> Note:Natural Earth is a small-scale cartographic dataset: highly urbanised cities (e.g. the cities of Metro Manila, Puerto Princesa) are separate units and some region names are outdated. For real work use the official boundaries (PSA/NAMRIA, also published as the COD-AB dataset on HDX).
url = "https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_1_states_provinces.zip"world_adm1 = gpd.read_file(url)ph = world_adm1[world_adm1["admin"] == "Philippines"][["name", "type_en", "region", "geometry"]].copy()ph = ph.rename(columns={"name": "Name", "type_en": "Type", "region": "Region"}).reset_index(drop=True)def island_group(region): """Assign an island group from the region name.""" r = region.lower() if "visayas" in r: return "Visayas" if any(k in r for k in ["mindanao", "zamboanga", "davao", "soccsksargen", "region xii", "region xiii", "armm"]): return "Mindanao" return "Luzon" # NCR, CAR, Ilocos, Cagayan Valley, Central Luzon, CALABARZON, MIMAROPA, Bicolph["Island_Group"] = ph["Region"].apply(island_group)# Area must be computed in a projected CRS (metres), never in degrees.# EPSG:32651 (UTM 51N) is a reasonable single zone for the whole country.ph["Area_km2"] = ph.to_crs(epsg=32651).area / 1e6print(f"✓ Loaded {len(ph)} administrative units, CRS = {ph.crs}")print(ph["Type"].value_counts().to_string())ph.head()3.2 Inspect the GeoDataFrame
print("Column types:")print(ph.dtypes, "\n")print("Units per island group:")print(ph["Island_Group"].value_counts(), "\n")xmin, ymin, xmax, ymax = ph.total_boundsprint(f"CRS: {ph.crs.name} (EPSG:{ph.crs.to_epsg()}), units: {ph.crs.axis_info[0].unit_name}")print(f"Extent: lon {xmin:.2f}–{xmax:.2f}°E, lat {ymin:.2f}–{ymax:.2f}°N")3.3 Filter and query
provinces = ph[ph["Type"] == "Province"]# Attribute filtermindanao = provinces[provinces["Island_Group"] == "Mindanao"]print(f"Mindanao provinces: {len(mindanao)}")# Numeric condition + sortinglargest = provinces.sort_values("Area_km2", ascending=False).head(5)print("\nFive largest provinces (km²):")print(largest[["Name", "Region", "Area_km2"]].round(0).to_string(index=False))# Combined conditionsbig_luzon = provinces[(provinces["Island_Group"] == "Luzon") & (provinces["Area_km2"] > 7000)]print(f"\nLuzon provinces larger than 7,000 km²: {sorted(big_luzon['Name'])}")3.4 Spatial operations: dissolve, buffer, intersectMetro Manila is split into 17 cities in this dataset. We dissolve them into one polygon, buffer it by 50 km (in metres, so in UTM) and find which units intersect the buffer.
ph_utm = ph.to_crs(epsg=32651)ncr = ph_utm[ph_utm["Region"] == "National Capital Region"].dissolve()print(f"Metro Manila (dissolved from {sum(ph_utm['Region'] == 'National Capital Region')} units): " f"{ncr.area.iloc[0] / 1e6:,.0f} km²")ncr_buffer = ncr.buffer(50_000) # 50 kmnear = ph_utm[ph_utm.intersects(ncr_buffer.iloc[0]) & (ph_utm["Region"] != "National Capital Region")]print(f"\nUnits within 50 km of Metro Manila ({len(near)}):")print(", ".join(sorted(near["Name"])))# Centroids: compute in the projected CRS, then convert back to lon/lat for displayph["centroid"] = ph_utm.centroid.to_crs(epsg=4326)3.5 Map the data
colors = {"Luzon": "#2ecc71", "Visayas": "#3498db", "Mindanao": "#e74c3c"}fig, axes = plt.subplots(1, 2, figsize=(16, 10))ph.plot(ax=axes[0], color=ph["Island_Group"].map(colors), edgecolor="black", linewidth=0.3)axes[0].legend(handles=[Patch(facecolor=c, label=g) for g, c in colors.items()], title="Island group", loc="upper left")axes[0].set_title("Administrative units by island group")ph.plot(ax=axes[1], column="Area_km2", cmap="YlGn", edgecolor="black", linewidth=0.3, legend=True, legend_kwds={"label": "Area (km²)", "shrink": 0.6})axes[1].set_title("Choropleth: unit area")for ax in axes: ax.set_xlabel("Longitude (°E)"); ax.set_ylabel("Latitude (°N)")plt.tight_layout(); plt.show()Add a web basemap with contextily. Basemap tiles are in Web Mercator (EPSG:3857), so we reproject first. (Needs internet; the cell skips the basemap if tiles cannot be fetched.)
import contextily as ctxluzon_web = ph[ph["Island_Group"] == "Luzon"].to_crs(epsg=3857)fig, ax = plt.subplots(figsize=(10, 12))luzon_web.plot(ax=ax, facecolor="none", edgecolor="darkblue", linewidth=0.8)try: ctx.add_basemap(ax, source=ctx.providers.CartoDB.Positron)except Exception as e: print(f"Basemap not available ({type(e).__name__}); showing boundaries only")ax.set_title("Luzon administrative units on a CartoDB Positron basemap")ax.set_axis_off(); plt.show()📝 Exercise 1: Map your home province1. Select one province by name (e.g. "Bohol", "Iloilo", "Bukidnon")2. Print its region and area in km²3. Plot it on its own, with its neighbours (units that touches it) in greyHint: ph[ph["Name"] == "Bohol"], ph[ph.touches(geom)]Expected output: a map with your province highlighted and a printed line such as Bohol – Central Visayas (Region VII) – 4,800 km² (areas from Natural Earth are approximate).
# TODO: Exercise 1my_name = "Bohol"# my_prov = ...# neighbours = ...# print(...)# fig, ax = plt.subplots(figsize=(8, 8))# ...Show solution
pythonmy_name = "Bohol"my_prov = ph[ph["Name"] == my_name]geom = my_prov.geometry.iloc[0]neighbours = ph[ph.touches(geom)]r = my_prov.iloc[0]print(f"{r['Name']} – {r['Region']} – {r['Area_km2']:,.0f} km²")fig, ax = plt.subplots(figsize=(8, 8))neighbours.plot(ax=ax, color="lightgrey", edgecolor="white")my_prov.plot(ax=ax, color="forestgreen", edgecolor="black")ax.set_title(f"{my_name} and neighbouring units")plt.show()Island provinces such as Bohol have no touching neighbours — try ph[ph.distance(geom) < 0.5] instead (distance in degrees here, so only for a rough look).
—## Part 4: Rasterio for Raster DataRasterio reads and writes gridded data (GeoTIFF, COG…) as NumPy arrays plus georeferencing (CRS + affine transform).### 4.1 Search Sentinel-2 L2A with STACSTAC (SpatioTemporal Asset Catalog) is the standard way to search EO archives. Microsoft Planetary Computer hosts Sentinel-2 L2A as Cloud-Optimized GeoTIFFs (COGs); planetary_computer.sign_inplace adds a short-lived access token to each asset URL — no account required. The same pystac-client code works with the Copernicus Data Space Ecosystem and the CopPhil Infrastructure STAC catalogues.Our area of interest is around Puerto Princesa, Palawan: city, forest, farmland and sea in one 10 × 10 km window.
from pystac_client import Clientimport planetary_computeraoi_lon, aoi_lat = 118.75, 9.80 # Puerto Princesa area, Palawanaoi_point = {"type": "Point", "coordinates": [aoi_lon, aoi_lat]}catalog = Client.open("https://planetarycomputer.microsoft.com/api/stac/v1", modifier=planetary_computer.sign_inplace)search = catalog.search( collections=["sentinel-2-l2a"], intersects=aoi_point, datetime="2024-01-01/2024-12-31", query={"eo:cloud_cover": {"lt": 10}},)items = list(search.items())print(f"✓ Found {len(items)} scenes with < 10% cloud cover")# Least cloudy scene (ties broken by ID so the choice is reproducible)item = sorted(items, key=lambda it: (it.properties["eo:cloud_cover"], it.id))[0]print(f"\nSelected: {item.id}")print(f" Date: {item.datetime:%Y-%m-%d}")print(f" Cloud cover: {item.properties['eo:cloud_cover']:.2f}%")print(f" Platform: {item.properties.get('platform')}")print(f" Baseline: {item.properties.get('s2:processing_baseline')}")print(f" MGRS tile: {item.properties.get('s2:mgrs_tile')}")4.2 Read a 10 × 10 km window from the cloudA full Sentinel-2 tile is 10,980 × 10,980 pixels per 10 m band. With COGs we read only the window we need: convert our lon/lat to the tile’s CRS (UTM), find the pixel, and read 1000 × 1000 pixels around it.
bands = {"blue": "B02", "green": "B03", "red": "B04", "nir": "B08"}size = 1000with rasterio.open(item.assets["B04"].href) as src: xs, ys = warp_transform("EPSG:4326", src.crs, [aoi_lon], [aoi_lat]) row, col = src.index(xs[0], ys[0]) col_off = int(np.clip(col - size // 2, 0, src.width - size)) row_off = int(np.clip(row - size // 2, 0, src.height - size)) window = Window(col_off, row_off, size, size) transform = src.window_transform(window) crs = src.crs print(f"Tile CRS: {crs}, full size {src.width} x {src.height} px") print(f"Window: col {col_off}, row {row_off}, {size} x {size} px")dn = {}for name, asset in bands.items(): with rasterio.open(item.assets[asset].href) as src: dn[name] = src.read(1, window=window) print(f" ✓ {asset} ({name}) dtype={dn[name].dtype}")4.3 From digital numbers to surface reflectanceSentinel-2 L2A stores reflectance as integers. Since processing baseline 04.00 (25 January 2022) products include an offset: \[\rho = \frac{DN + \text{BOA\_ADD\_OFFSET}}{10000}, \quad \text{BOA\_ADD\_OFFSET} = -1000\]Forgetting the offset biases every index you compute (this is the same issue that Earth Engine’s S2_SR_HARMONIZED collection solves for you, see Session 1). DN = 0 means no data.
baseline = float(item.properties.get("s2:processing_baseline", "0"))offset = -1000 if baseline >= 4.0 else 0print(f"Processing baseline {baseline:.2f} → offset {offset}")def to_reflectance(arr): refl = (arr.astype("float32") + offset) / 10000.0 refl[arr == 0] = np.nan # nodata return np.clip(refl, 0, 1.5)blue, green, red, nir = (to_reflectance(dn[b]) for b in ["blue", "green", "red", "nir"])height, width = red.shapeprint(f"✓ Reflectance arrays {height} x {width}, valid pixels: {np.isfinite(red).mean():.1%}")4.4 Save as a GeoTIFF and inspect its metadataWriting a multi-band GeoTIFF needs a profile: size, band count, data type, CRS, transform, nodata. Re-opening the file shows the metadata every raster carries.
raster_path = os.path.join(out_dir, "palawan_s2_subset.tif")profile = {"driver": "GTiff", "height": height, "width": width, "count": 4, "dtype": "float32", "crs": crs, "transform": transform, "nodata": np.nan, "compress": "deflate"}with rasterio.open(raster_path, "w", **profile) as dst: for i, (arr, desc) in enumerate(zip([blue, green, red, nir], ["Blue B02", "Green B03", "Red B04", "NIR B08"]), start=1): dst.write(arr, i) dst.set_band_description(i, desc)with rasterio.open(raster_path) as src: print(f"File: {os.path.basename(raster_path)} ({os.path.getsize(raster_path) / 1e6:.1f} MB)") print(f"Size: {src.width} x {src.height} px, {src.count} bands, {src.dtypes[0]}") print(f"CRS: {src.crs}") print(f"Resolution: {src.res} m") print(f"Bounds: {src.bounds}") print(f"Bands: {src.descriptions}") print(f"Transform:\n{src.transform}") raster_crs, raster_bounds = src.crs, src.bounds4.5 Band statistics
stats = pd.DataFrame({ name: {"min": np.nanmin(a), "p2": np.nanpercentile(a, 2), "median": np.nanmedian(a), "mean": np.nanmean(a), "p98": np.nanpercentile(a, 98), "max": np.nanmax(a)} for name, a in {"Blue B02": blue, "Green B03": green, "Red B04": red, "NIR B08": nir}.items()}).Tstats.round(3)Typical values: water has very low NIR (< 0.05); healthy vegetation has NIR around 0.25–0.45 and red below 0.05.
4.6 Single bands
fig, axes = plt.subplots(2, 2, figsize=(12, 11))for ax, (arr, title, cmap) in zip(axes.flat, [(blue, "Blue (B02)", "Blues_r"), (green, "Green (B03)", "Greens_r"), (red, "Red (B04)", "Reds_r"), (nir, "NIR (B08)", "gray")]): im = ax.imshow(arr, cmap=cmap, vmin=0, vmax=0.4) ax.set_title(title); ax.set_axis_off() plt.colorbar(im, ax=ax, fraction=0.046, label="Reflectance")plt.suptitle(f"Sentinel-2 10 m bands, Puerto Princesa area ({item.datetime:%Y-%m-%d})", fontsize=14)plt.tight_layout(); plt.show()4.7 True colour and false colour compositesA composite stacks three bands into the R, G, B channels. A percentile stretch (2–98 %) makes the image readable. In the false colour (NIR-Red-Green) composite, vegetation appears red because plants reflect strongly in the near-infrared.
def stretch(rgb, lo=2, hi=98): p_lo, p_hi = np.nanpercentile(rgb, (lo, hi)) return np.clip((rgb - p_lo) / (p_hi - p_lo), 0, 1)true_color = stretch(np.dstack([red, green, blue]))false_color = stretch(np.dstack([nir, red, green]))fig, axes = plt.subplots(1, 2, figsize=(16, 8))axes[0].imshow(np.nan_to_num(true_color)); axes[0].set_title("True colour (B04-B03-B02)")axes[1].imshow(np.nan_to_num(false_color)); axes[1].set_title("False colour (B08-B04-B03): vegetation in red")for ax in axes: ax.set_axis_off()plt.tight_layout(); plt.show()4.8 NDVI| NDVI | Typical surface ||—|—|| < 0 | Water || 0 – 0.2 | Bare soil, built-up, sand || 0.2 – 0.5 | Sparse / moderate vegetation, cropland || 0.5 – 0.8 | Dense vegetation || > 0.8 | Very dense canopy (tropical forest) |These thresholds are rules of thumb; they vary with season, sensor and atmospheric correction.
ndvi = calculate_ndvi(nir, red)pixel_area_km2 = abs(transform.a * transform.e) / 1e6 # 10 m x 10 m = 0.0001 km²classes = {"Water (<0)": ndvi < 0, "Bare/built (0-0.2)": (ndvi >= 0) & (ndvi < 0.2), "Moderate (0.2-0.5)": (ndvi >= 0.2) & (ndvi < 0.5), "Dense (0.5-0.8)": (ndvi >= 0.5) & (ndvi < 0.8), "Very dense (>0.8)": ndvi >= 0.8}summary = pd.DataFrame({"pixels": {k: int(v.sum()) for k, v in classes.items()}})summary["area_km2"] = summary["pixels"] * pixel_area_km2summary["percent"] = 100 * summary["pixels"] / np.isfinite(ndvi).sum()print(f"NDVI mean {np.nanmean(ndvi):.3f}, median {np.nanmedian(ndvi):.3f}")summary.round(2)fig, ax = plt.subplots(figsize=(10, 9))im = ax.imshow(ndvi, cmap="RdYlGn", vmin=-0.2, vmax=0.9, extent=plotting_extent(ndvi, transform))plt.colorbar(im, ax=ax, shrink=0.8, label="NDVI")ax.set_title("NDVI, Puerto Princesa area")ax.set_xlabel("Easting (m, UTM)"); ax.set_ylabel("Northing (m, UTM)")plt.show()4.9 NDVI distribution
vals = ndvi[np.isfinite(ndvi)]fig, ax = plt.subplots(figsize=(12, 5))ax.hist(vals, bins=100, color="green", alpha=0.7)ax.axvline(np.mean(vals), color="red", ls="--", label=f"mean {np.mean(vals):.2f}")ax.axvline(np.median(vals), color="blue", ls="--", label=f"median {np.median(vals):.2f}")for t in [0, 0.2, 0.5, 0.8]: ax.axvline(t, color="black", ls=":", alpha=0.5)ax.set_xlabel("NDVI"); ax.set_ylabel("Pixel count"); ax.set_title("NDVI histogram")ax.legend(); plt.show()A bimodal histogram (one peak below 0, one around 0.7–0.8) is typical of a coastal scene: water vs vegetated land.
📝 Exercise 2: NDWI water indexThe (McFeeters) Normalized Difference Water Index highlights open water:\[NDWI = \frac{Green - NIR}{Green + NIR}\]1. Write calculate_ndwi(green, nir) (re-use the pattern of calculate_ndvi)2. Compute NDWI for the subset and map it with the "Blues" colormap3. Create a water mask ndwi > 0 and compute the water area in km²Expected output: a map where Puerto Princesa Bay and the open sea are bright, and a water area of several tens of km² (exact value depends on the scene).
# TODO: Exercise 2# def calculate_ndwi(green, nir):# ...# ndwi = ...# water_km2 = ...Show solution
pythondef calculate_ndwi(green, nir): green = np.asarray(green, dtype="float32"); nir = np.asarray(nir, dtype="float32") denom = green + nir with np.errstate(divide="ignore", invalid="ignore"): return np.where(denom != 0, (green - nir) / denom, np.nan)ndwi = calculate_ndwi(green, nir)water = ndwi > 0water_km2 = water.sum() * pixel_area_km2print(f"NDWI range {np.nanmin(ndwi):.2f} to {np.nanmax(ndwi):.2f}; water area {water_km2:.1f} km²")fig, axes = plt.subplots(1, 2, figsize=(16, 8))im = axes[0].imshow(ndwi, cmap="Blues", vmin=-0.6, vmax=0.6); plt.colorbar(im, ax=axes[0], shrink=0.7)axes[0].set_title("NDWI")axes[1].imshow(water, cmap="Blues"); axes[1].set_title(f"Water mask (NDWI > 0): {water_km2:.1f} km²")for ax in axes: ax.set_axis_off()plt.show()
—## Part 5: Combining Vector and Raster DataThe golden rule: bring both datasets into the same CRS before combining them. Our boundaries are in EPSG:4326 (degrees), the Sentinel-2 tile in UTM (metres).### 5.1 Clip the raster to a boundaryNatural Earth stores Puerto Princesa City separately from Palawan province, so we dissolve both into one “Palawan” polygon, reproject it to the raster CRS and clip with rasterio.mask.
print(f"Vector CRS: {ph.crs} Raster CRS: {raster_crs}")palawan = ph[ph["Name"].isin(["Palawan", "Puerto Princesa"])].dissolve()palawan_r = palawan.to_crs(raster_crs)with rasterio.open(raster_path) as src: clipped, clip_transform = rasterio_mask(src, palawan_r.geometry, crop=True, nodata=np.nan)clipped_ndvi = calculate_ndvi(clipped[3], clipped[2])land_share = np.isfinite(clipped_ndvi).sum() / np.isfinite(ndvi).sum()print(f"✓ Clipped to the Palawan boundary: {clipped.shape[2]} x {clipped.shape[1]} px")print(f" Share of the subset on land (inside the boundary): {land_share:.1%}")print(f" Mean NDVI on land: {np.nanmean(clipped_ndvi):.3f} (whole subset: {np.nanmean(ndvi):.3f})")5.2 Overlay boundaries on the raster
subset_box = gpd.GeoDataFrame(geometry=[box(*raster_bounds)], crs=raster_crs)units_r = ph.drop(columns="centroid").to_crs(raster_crs)units_r = units_r[units_r.intersects(subset_box.geometry.iloc[0])]fig, ax = plt.subplots(figsize=(10, 10))im = ax.imshow(ndvi, cmap="RdYlGn", vmin=-0.2, vmax=0.9, extent=plotting_extent(ndvi, transform))units_r.boundary.plot(ax=ax, edgecolor="blue", linewidth=2)ax.set_xlim(raster_bounds.left, raster_bounds.right); ax.set_ylim(raster_bounds.bottom, raster_bounds.top)plt.colorbar(im, ax=ax, shrink=0.7, label="NDVI")ax.set_title("NDVI with administrative boundaries (both in UTM)")plt.show()print("Units in view:", ", ".join(units_r["Name"]))5.3 Zonal statisticsZonal statistics summarise raster values inside each polygon — the basis of many EO indicators (e.g. mean NDVI per municipality). Here we rasterise each polygon to a mask with geometry_mask (the rasterstats or exactextract packages do the same at scale).
rows = []for _, unit in units_r.iterrows(): inside = ~geometry_mask([unit.geometry], out_shape=ndvi.shape, transform=transform) v = ndvi[inside & np.isfinite(ndvi)] if v.size: rows.append({"Name": unit["Name"], "pixels": v.size, "area_km2": v.size * pixel_area_km2, "ndvi_mean": v.mean(), "ndvi_median": np.median(v), "veg_share_%": 100 * (v > 0.5).mean()})zonal = pd.DataFrame(rows).round(3)zonal5.4 Save results
ndvi_path = os.path.join(out_dir, "palawan_ndvi.tif")with rasterio.open(ndvi_path, "w", driver="GTiff", height=height, width=width, count=1, dtype="float32", crs=crs, transform=transform, nodata=np.nan, compress="deflate") as dst: dst.write(ndvi.astype("float32"), 1) dst.set_band_description(1, f"NDVI from {item.id}")gpkg_path = os.path.join(out_dir, "philippines_adm1.gpkg")ph.drop(columns="centroid").to_file(gpkg_path, layer="adm1", driver="GPKG")print("✓ Saved:")for p in [raster_path, ndvi_path, gpkg_path]: print(f" {p} ({os.path.getsize(p) / 1e6:.1f} MB)")—## Part 6: Best Practices and Common PitfallsMemory- Open files with context managers: with rasterio.open(path) as src: ...- Read only what you need: one band (src.read(1)), a window (window=Window(...)), or a decimated overview (out_shape=(500, 500))- Process very large rasters block by block: for _, win in src.block_windows(1): ...CRS- Always check gdf.crs and src.crs before combining; reproject vectors with gdf.to_crs(src.crs)- Compute areas and distances in a projected CRS. Common choices for the Philippines: EPSG:32650 (UTM 50N, Palawan and the west), EPSG:32651 (UTM 51N, most of Luzon and Visayas, Metro Manila), EPSG:32652 (UTM 52N, eastern Mindanao); PRS92 zones EPSG:3121–3125 for national mapping productsNoData and scaling- Mask nodata before statistics (src.read(1, masked=True) or NaN + np.nanmean)- Apply scale and offset: Sentinel-2 L2A after Jan 2022 needs the −1000 offsetCommon errors| Error | Typical cause | Fix ||—|—|—|| ValueError: Input shapes do not overlap raster | Vector and raster in different CRS | gdf.to_crs(src.crs) || CRSError / wrong areas | Area computed in degrees | Project to UTM first || RasterioIOError on a signed URL | Planetary Computer token expired (~1 h) | Re-run the search cell || MemoryError | Reading a full tile | Use windows or out_shape |
# A quick CRS check you can copy into your own projectsdef check_crs(gdf, raster_path): with rasterio.open(raster_path) as src: same = gdf.crs == src.crs print(f"Vector: {gdf.crs.to_string()} | Raster: {src.crs.to_string()} | same: {same}") return gdf if same else gdf.to_crs(src.crs)_ = check_crs(ph.drop(columns="centroid"), raster_path)—## Recap- GeoPandas: read boundaries, filter by attributes, dissolve, buffer, intersect, map — always compute areas in a projected CRS- STAC + COGs: search an archive by place/time/cloud cover and stream only the pixels you need- Rasterio: windows, profiles, transforms; write and re-read GeoTIFFs- Sentinel-2 L2A: reflectance = (DN − 1000) / 10000 for products since baseline 04.00- Indices: NDVI for vegetation, NDWI for water- Vector + raster: same CRS first; clip, overlay, zonal statisticsThese are the building blocks of every ML workflow in the rest of the course: preparing training samples (Day 2), image chips and masks (Day 3) and time series (Day 4).## Next: Session 4 — Google Earth Enginepythonimport eeee.Authenticate()ee.Initialize(project="your-cloud-project") # Earth Engine now requires a Cloud projects2 = (ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED") # offset already harmonised .filterBounds(ee.Geometry.Point([118.75, 9.80])) .filterDate("2024-01-01", "2024-12-31"))ndvi = s2.median().normalizedDifference(["B8", "B4"])## Optional practice- A. Repeat Part 4 for another area (e.g. rice areas in Nueva Ecija, ~120.9°E 15.6°N) and compare NDVI distributions- B. Implement EVI or SAVI and compare them with NDVI over dense forest- C. Search two dates (dry season vs wet season) and map the NDVI difference- D. Download official boundaries (COD-AB from HDX) and redo the zonal statistics per municipality## Resources- GeoPandas: https://geopandas.org/ · Rasterio: https://rasterio.readthedocs.io/ · pystac-client: https://pystac-client.readthedocs.io/- Planetary Computer Sentinel-2 L2A: https://planetarycomputer.microsoft.com/dataset/sentinel-2-l2a- Carpentries — Introduction to Geospatial Raster and Vector Data with Python: https://carpentries-incubator.github.io/geospatial-python/- Earth Data Science: https://www.earthdatascience.org/- Philippine data: PhilSA https://philsa.gov.ph/ · NAMRIA Geoportal https://www.geoportal.gov.ph/ · HDX Philippines https://data.humdata.org/group/phl—EO AI/ML Training · Dimitrios Kasampalis (Anefelo) · CC BY-SA 4.0