Skip to main content

Digital Elevation Models (DEM)

Code
from pystac_client import Client
import rasterio
from rasterio.windows import from_bounds
from rasterio.merge import merge
from pyproj import Transformer
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import psutil
import os 
from dotenv import load_dotenv
load_dotenv()
True

A digital elevation model is a digital representation of the altitude of the Earth’s surface, in which each grid cell holds an elevation value. It is commonly used to analyze slopes and relief for infrastructure projects and urban planning. It is also widely used in hydrology for water runoff, watersheds and flood risk analysis.

We will use the Copernicus DEM, which is produced mainly from radar data acquired by the TanDEM-X space mission (Airbus/DLR). The satellites acquired radar images of the Earth’s surface from different positions; using radar interferometry (InSAR), the altitude of surface points could be computed. These data were then processed, corrected and edited to produce a continuous elevation surface. The result is available at, among other resolutions, 30 m (GLO-30) and 90 m (GLO-90).

An important point is that the Copernicus DEM is a Digital Surface Model (DSM), not a Digital Terrain Model (DTM), which would represent the altitude of each point regardless of what covers the surface. So the Copernicus DSM can include the height of buildings, trees and other structures. Despite corrections that improve the quality of the model, these artifacts are not systematically removed, because the model aims to represent the Earth’s surface rather than the bare terrain itself.

Colab link

Open In Colab
Code
# only run this if you are on Colab! 
# git clone https://github.com/ftl-brazil-2026/ebook.git
# pip install -r requirements.txt

API access keys

To download the rasters for our analysis, we first need to register an API key with CDSE. See the last class for an explanation of how to create this key.

Code
#os.environ["GDAL_HTTP_TCP_KEEPALIVE"] = "YES"
os.environ["AWS_S3_ENDPOINT"] = "eodata.dataspace.copernicus.eu"
os.environ["AWS_ACCESS_KEY_ID"] = os.environ.get("CDSE_CLIENT")
os.environ["AWS_SECRET_ACCESS_KEY"] = os.environ.get("CDSE_SECRET")
os.environ["AWS_HTTPS"] = "YES"
os.environ["AWS_VIRTUAL_HOSTING"] = "FALSE"

# AWS-style endpoint for the Copernicus ecosystem in STAC
cdse_stac = "https://stac.dataspace.copernicus.eu/v1/"
client = Client.open(cdse_stac)

Accessing the collection through STAC

Code
client.get_collection('cop-dem-glo-30-dged-cog')
<CollectionClient id=cop-dem-glo-30-dged-cog>

Defining a bbox of interest

Here we will analyze an area on the São Paulo coast, famous for the Serra do Mar mountain range and the classic photos we see on social media.

alt text
Code
## my bbox for Cubatão
bbox = [-46.80215, -24.10, -46.158748, -23.754701]
Code
import folium
from shapely.geometry import box

bounds_polygon = box(*bbox)

centro_lat = (bbox[1] + bbox[3]) / 2
centro_lon = (bbox[0] + bbox[2]) / 2

m = folium.Map(location=[centro_lat, centro_lon], zoom_start=10)


folium.GeoJson(
    bounds_polygon.__geo_interface__,
    name="Bounds",
    style_function=lambda x: {
        'fillColor': 'none',
        'color': 'blue',
        'weight': 3,
        'fillOpacity': 0
    }
).add_to(m)

m
Make this Notebook Trusted to load map: File -> Trust Notebook

Accessing the image catalog

Code
dem = client.search(
    collections=["cop-dem-glo-30-dged-cog"],
    bbox=bbox
)
Code
for item in dem.items():
    print(item)
<Item id=Copernicus_DSM_COG_10_S25_00_W047_00_DEM>
<Item id=Copernicus_DSM_COG_10_S24_00_W047_00_DEM>
Code
# Collect the two DEM assets
dem_paths = [
    item.assets["data"].href
    for item in dem.items()
]
Code
dem_paths
['s3://eodata/auxdata/CopDEM_COG/copernicus-dem-30m/Copernicus_DSM_COG_10_S25_00_W047_00_DEM/Copernicus_DSM_COG_10_S25_00_W047_00_DEM.tif',
 's3://eodata/auxdata/CopDEM_COG/copernicus-dem-30m/Copernicus_DSM_COG_10_S24_00_W047_00_DEM/Copernicus_DSM_COG_10_S24_00_W047_00_DEM.tif']
Code


# Open the DEMs as Rasterio datasets
srcs = [rasterio.open(path) for path in dem_paths]

try:
    # CRS of the DEMs
    dem_crs = srcs[0].crs

    # Transform bbox from EPSG:4326 to DEM CRS
    transformer = Transformer.from_crs(
        "EPSG:4326",
        dem_crs,
        always_xy=True
    )

    minx, miny = transformer.transform(bbox[0], bbox[1])
    maxx, maxy = transformer.transform(bbox[2], bbox[3])

    # Merge the two DEM tiles and clip to bbox
    mosaic, mosaic_transform = merge(
        srcs,
        bounds=(minx, miny, maxx, maxy),
        masked=True
    )

    # Remove the band dimension
    dem_array = mosaic[0]

finally:
    # Close the datasets
    for src in srcs:
        src.close()

print("Shape:", dem_array.shape)
print("CRS:", dem_crs)
print("Transform:", mosaic_transform)
Shape: (1243, 2316)
CRS: EPSG:4326
Transform: | 0.00, 0.00,-46.80|
| 0.00,-0.00,-23.75|
| 0.00, 0.00, 1.00|
Code
dem_array
masked_array(
  data=[[757.687744140625, 758.630126953125, 758.8342895507812, ...,
         734.3363647460938, 737.7005615234375, 733.650634765625],
        [761.6920166015625, 759.5462646484375, 759.8544921875, ...,
         735.8826904296875, 737.18115234375, 737.0667724609375],
        [764.2097778320312, 760.8612670898438, 761.0741577148438, ...,
         734.8046264648438, 736.7730102539062, 736.5520629882812],
        ...,
        [8.038652420043945, 5.4134016036987305, 6.642546653747559, ...,
         --, --, --],
        [6.919680118560791, 6.8587799072265625, 6.9172043800354, ..., --,
         --, --],
        [--, --, --, ..., --, --, --]],
  mask=[[False, False, False, ..., False, False, False],
        [False, False, False, ..., False, False, False],
        [False, False, False, ..., False, False, False],
        ...,
        [False, False, False, ...,  True,  True,  True],
        [False, False, False, ...,  True,  True,  True],
        [ True,  True,  True, ...,  True,  True,  True]],
  fill_value=0.0,
  dtype=float32)

Visualizing the DEM

We now have an array with the elevation of Cubatão/SP (at the foot of the Serra do Mar). The region goes from almost sea level to over 1,100 m within a very short distance, because of the escarpment. This will make the contour lines very interesting to look at.

Let’s create two kinds of visualization: 1. A simple elevation map (each color = one height); 2. A shaded relief (hillshade), which simulates sunlight coming from an angle to highlight the relief.

Code
fig, ax = plt.subplots(figsize=(10, 6))
im = ax.imshow(dem_array, cmap="terrain")
fig.colorbar(im, ax=ax, label="Elevation (m)")
ax.set_title("Digital Elevation Model of Cubatão/SP (Copernicus DEM 30m)")
ax.axis("off")
plt.show()

Characteristics of Digital Elevation Models

Here we can compute some terrain characteristics such as hillshade, slope angle and aspect, which is basically the compass direction a face of the terrain is pointing to.

This can be extremely useful for planning. Example: you are analyzing a plot for a buyer who would like the bedroom of the house to face north. We also need these characteristics to build contour lines, as well as for hydrological analysis.

Here is a super important detail we’ve already covered in other classes: the COORDINATE SYSTEM. This DEM is in EPSG:4326 (degrees, not meters; an unprojected geographic system). For the shading to have the right proportions, we need to convert the pixel size from degrees to meters before computing the slope, that is, project to the UTM zone of our study area.

Code
mosaic_transform.
Affine(0.0002777777777777778, 0.0, -46.80215,
       0.0, -0.0002777777777777778, -23.754701)
Code
import xarray as xr
import rioxarray  

# get the number of columns and rows 
rows, cols = dem_array.shape

## transform each column and row with the CRS affine transform
## adding 0.5 moves the position from the corner to the center of each pixel
## think of a raster pixel whose upper-left corner is at coordinate 100 and which is 30 m wide
## to move to the middle, we add 15 m, i.e. 0.5 times the pixel size.
xs = mosaic_transform.c + (np.arange(cols) + 0.5) * mosaic_transform.a
ys = mosaic_transform.f + (np.arange(rows) + 0.5) * mosaic_transform.e

# let's create an XARRAY to use the existing functions 
dem_da = xr.DataArray(
    np.ma.filled(dem_array, np.nan),
    dims=("y", "x"),
    coords={"y": ys, "x": xs},
    name="elevation",
)
# Here we set the CRS, which is 4326 - WGS84
dem_da = dem_da.rio.write_crs(dem_crs)

# xarray has handy functions to estimate the CRS, although we could also reproject by hand. 
utm_crs = dem_da.rio.estimate_utm_crs()
dem_utm = dem_da.rio.reproject(utm_crs)
dem_utm.rio.write_nodata(np.nan, inplace=True)

print("Estimated CRS:", utm_crs)
print("shape:", dem_utm.shape, "| resolution (m):", dem_utm.rio.resolution())
CRS estimado: EPSG:32723
shape: (1349, 2284) | resolução (m): (28.85130642918404, -28.85130642918404)
Code
xs
array([-46.80201111, -46.80173333, -46.80145556, ..., -46.15951111,
       -46.15923333, -46.15895556], shape=(2316,))

Spatial Analysis of Digital Elevation Models

Once our data is in xarray and projected, we can carry out these analyses very easily. We could also do the same calculations in NumPy, but it is much more work and more error-prone.

The xarray-spatial library already provides these functions, tested and optimized. Xarray is essentially a NumPy array with names, coordinates and metadata attached, forming a 3D or 4D cube (x, y, z, time) for any variable. Xarray lets us work with data collections with many, many variables, such as the ERA5 dataset, which contains lots of climate data in a single dataset.

We will go deeper into xarray next week, but today we’ll have a brief introduction to how the library works.

Let’s look at three classic terrain analyses: hillshade, slope and aspect (orientation).

The idea is that for each pixel, we first compute the slope and then the direction of the slope (aspect) of the terrain. Finally, we simulate sunlight from a chosen azimuth and altitude angle.

Just out of curiosity, let's see how to compute everything xarray offers using NumPy, and then do the same in xarray!

Code
def hillshade(array, azimuth=315, angle_altitude=45, 
              cellsize_x=30, cellsize_y=30
              ):
    """Computes a shaded relief from a DEM."""
    data = np.ma.filled(array, np.nan).astype("float64")
    dy, dx = np.gradient(data, cellsize_y, cellsize_x)
    slope = np.pi / 2 - np.arctan(np.hypot(dx, dy))
    aspect = np.arctan2(-dx, dy)

    azimuth_rad = np.radians(360 - azimuth + 90)
    altitude_rad = np.radians(angle_altitude)

    shaded = (np.sin(altitude_rad) * np.sin(slope)
              + np.cos(altitude_rad) * np.cos(slope) * np.cos(azimuth_rad - aspect))
    return np.clip(shaded, 0, 1)


# nominal resolution of the Copernicus DEM 30m. 1 arc-second (degrees) > meters
resolucao_graus = 1 / 3600
lat_media = (bbox[1] + bbox[3]) / 2
cellsize_y = resolucao_graus * 111_320
cellsize_x = resolucao_graus * 111_320 * np.cos(np.radians(lat_media))

shade = hillshade(dem_array, cellsize_x=cellsize_x, cellsize_y=cellsize_y)

fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(shade, cmap="gray")
im = ax.imshow(dem, cmap="terrain", alpha=0.5)
fig.colorbar(im, ax=ax, label="Elevation (m)")
ax.set_title("DEM with shaded relief - NUMPY")
ax.axis("off")
plt.show()

Slope

Slope measures how steep the terrain is at each pixel, in degrees, where 0° is completely flat and 90° would be a vertical wall. It is one of the most widely used metrics in geomorphology: landslide risk, erosion, how hard a trail is, whether you can build somewhere, all depend on the slope of the terrain.

Code
from xrspatial import slope as xrs_slope

slope_da = xrs_slope(dem_utm)

fig, ax = plt.subplots(figsize=(10, 6))
im = ax.imshow(slope_da, cmap="YlOrRd", vmin=0, vmax=60)
fig.colorbar(im, ax=ax, label="Slope (degrees)")
ax.set_title("Slope — Cubatão/SP")
ax.axis("off")
plt.show()

print(f"Mean slope: {float(slope_da.mean()):.1f}°  |  max: {float(slope_da.max()):.1f}°")

Inclinação média: 12.2°  |  máxima: 67.6°

Aspect (orientation)

Aspect indicates which direction the slope faces. It goes from 0° to 360°, like a compass (0°/360° = North, 90° = East, 180° = South, 270° = West). It matters because, in the southern hemisphere, north-facing slopes get more sun throughout the year (and south-facing ones less), affecting the environment: vegetation, soil moisture and even microclimate. Perfectly flat terrain theoretically has no defined direction, and the library marks those pixels with -1.

Since aspect “wraps around” (0° and 360° are the same direction), we use a cyclic colormap instead of a linear one.

Code
from xrspatial import aspect as xrs_aspect

aspect_da = xrs_aspect(dem_utm)
aspect_plot = aspect_da.where(aspect_da >= 0)  # hide flat pixels (-1) from the map

fig, ax = plt.subplots(figsize=(10, 6))
im = ax.imshow(aspect_plot, cmap="twilight", vmin=0, vmax=360)
fig.colorbar(im, ax=ax, label="Aspect (degrees, 0°=North)")
ax.set_title("Aspect — Cubatão/SP")
ax.axis("off")
plt.show()

Hillshade

Same calculation as before, but with the library’s ready-made implementation. We simulate sunlight coming from a chosen azimuth and altitude.

Code
from xrspatial import hillshade as xrs_hillshade

shade_xrs = xrs_hillshade(dem_utm, 
                          azimuth=315, 
                          angle_altitude=45)

fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(shade_xrs, cmap="terrain")
ax.set_title("Hillshade (xarray-spatial)")
#fig.colorbar(im, ax=ax, label="Elevation (m)")
ax.axis("off")
plt.show()

Contour lines

A contour line connects all points with the same elevation. Let’s generate contours every 100 meters, the same interval we’ll use later when we turn these contours into vectors.

For now this is just a visualization (matplotlib computes the contours on the array, in pixel coordinates that are not yet georeferenced vector objects). In the next step we’ll extract these same contours as vector geometries.

Code
intervalo = 100  # meters

nivel_min = np.floor(dem_array.min()/intervalo) *intervalo
nivel_max = np.ceil(dem_array.max()/intervalo) *intervalo 

niveis = np.arange(nivel_min, nivel_max + intervalo, intervalo)
print("Levels (m):", niveis)
Níveis (m): [-100.    0.  100.  200.  300.  400.  500.  600.  700.  800.  900. 1000.
 1100. 1200.]
Code
intervalo = 100  # meters

nivel_min = np.floor(dem_array.min()/intervalo) *intervalo
nivel_max = np.ceil(dem_array.max()/intervalo) *intervalo 

niveis = np.arange(nivel_min, nivel_max + intervalo, intervalo)
print("Levels (m):", niveis)

fig, ax = plt.subplots(figsize=(10, 6))
im = ax.imshow(dem_array, cmap="terrain")
fig.colorbar(im, ax=ax, label="Elevation (m)")

contornos = ax.contour(dem_array, levels=niveis, colors="black", linewidths=0.4)
# only label every 200 m (every 100 m is unreadable on the plateau, where the relief is gentler)
ax.clabel(contornos, levels=niveis[::2], inline=True, fontsize=7, fmt="%d m")

ax.set_title(f"Contour lines every {intervalo} m")
ax.axis("off")
plt.show()
Níveis (m): [-100.    0.  100.  200.  300.  400.  500.  600.  700.  800.  900. 1000.
 1100. 1200.]

Code
len(contornos.allsegs)
14

Vectorizing: contour lines as a GeoDataFrame

The contours we just drew only exist inside the matplotlib object (contornos). They are great for visualization, but useless for anything else. If we want to apply all the spatial analyses we already know, we need to vectorize these lines.

The idea is simple: matplotlib has already computed, for each level, one or more lines, each as a list of points in pixel coordinates (cs.allsegs). We just need to:

  1. Take those points (column, row);
  2. Convert them to real coordinates (x, y) using the dem_transform we saved;
  3. Build a shapely LineString for each segment;
  4. Store everything in a GeoDataFrame, with the elevation as a regular column.

From then on, each contour line becomes a “real” line: you can do gdf.intersects(point), gdf.length, save it to disk, etc.

Code
import geopandas as gpd
from shapely.geometry import LineString
from rasterio.transform import xy as transform_xy


def contours_to_geodataframe(contour_set, transform, crs) -> gpd.GeoDataFrame:
    """Converts a matplotlib QuadContourSet into a GeoDataFrame of lines (one per segment)."""
    geometries = []
    elevations = []

    for level, segments in zip(contour_set.levels, contour_set.allsegs):
        for seg in segments:
            if len(seg) < 2:
                continue  # need at least 2 points to make a line
            cols, rows = seg[:, 0], seg[:, 1]
            xs, ys = transform_xy(transform, rows, cols)  # pixel to real coordinates
            geometries.append(LineString(zip(xs, ys)))
            elevations.append(level)

    return gpd.GeoDataFrame({"elevation": elevations}, geometry=geometries, crs=crs)


contornos_gdf = contours_to_geodataframe(contornos, mosaic_transform, dem_crs)
print(f"{len(contornos_gdf)} contour line segments")
contornos_gdf.head()
2221 segmentos de curva de nível
elevation geometry
0 0.0 LINESTRING (-46.35629 -23.92051, -46.35618 -23...
1 0.0 LINESTRING (-46.2872 -23.92123, -46.28729 -23....
2 0.0 LINESTRING (-46.35646 -23.92132, -46.35619 -23...
3 0.0 LINESTRING (-46.34866 -23.92178, -46.3486 -23....
4 0.0 LINESTRING (-46.31978 -23.92428, -46.31979 -23...
Code
contornos_gdf['elevation'].unique()
array([   0.,  100.,  200.,  300.,  400.,  500.,  600.,  700.,  800.,
        900., 1000., 1100.])
Code
fig, ax = plt.subplots(figsize=(10, 6))
contornos_gdf.plot(column="elevation", 
                   cmap="terrain", 
                   legend=True,
                    legend_kwds={"label": "Elevation (m)"}, 
                    linewidth=0.6, 
                    ax=ax)
ax.set_title("Contour lines as vectors, colored by height")
ax.set_aspect("equal")
plt.show()

Once we have vectorized this raster, we can apply any spatial analysis we already know

Code
from shapely import Point
# Example: let's find all contours less than 200 meters from a point

# for distance queries in meters, we reproject to a metric CRS
contornos_gdf_utm = contornos_gdf.to_crs(contornos_gdf.estimate_utm_crs())

# example point: -23.85, -46.7
ponto_exemplo = gpd.GeoDataFrame(geometry=[Point(-46.7,-23.85)],crs="4326").to_crs(contornos_gdf_utm.crs)
ponto = ponto_exemplo.geometry.iloc[0]

curvas_proximas = contornos_gdf_utm[contornos_gdf_utm.geometry.distance(ponto) < 500]
print(f"{len(curvas_proximas)} contour segments less than 200 m from the example point")
# this is exactly the kind of spatial query we'll use later to
# match points (e.g. springs, trails) with the nearest contour line
2 segmentos de curva a menos de 200 m do ponto de exemplo
Code
curvas_proximas
elevation geometry
1266 800.0 LINESTRING (327012.225 7361058.891, 327040.404...
1267 800.0 LINESTRING (326673.066 7361024.435, 326701.424...

Digital Elevation Model in 3D

We’ll use plotly.graph_objects.Surface, which renders an interactive 3D surface (you can rotate it, zoom and hover to see the exact elevation) without any heavy 3D library.

Two tricks for 3D visualization: - The grid has many pixels (hundreds of thousands), so we downsample it (::3) just to keep the interaction smooth in the browser; for a high-quality final image we could use the full resolution. If your computer is still slow, try downsampling even more. - Our area is much wider than it is tall (tens of km wide, ~1 km of relief), and if we plotted it at true scale the relief would look almost flat. So we apply a vertical exaggeration, a common practice in terrain visualization.

Code
import plotly.graph_objects as go

step = 3  # downsampling to keep the interaction smooth
dem_sample = dem_utm.values[::step, ::step]

x_res, y_res = dem_utm.rio.resolution()
x_extent = dem_sample.shape[1] * abs(x_res) * step
y_extent = dem_sample.shape[0] * abs(y_res) * step
z_extent = float(np.nanmax(dem_sample) - np.nanmin(dem_sample))

exagero_vertical = 3
aspect_z = (z_extent / x_extent) * exagero_vertical

fig = go.Figure(data=[go.Surface(z=dem_sample, colorscale="earth",
                                  colorbar=dict(title="m"))])
fig.update_layout(
    title=f"3D DEM — Cubatão/SP (vertical exaggeration {exagero_vertical}x)",
    scene=dict(
        xaxis_title="x (downsampled)",
        yaxis_title="y (downsampled)",
        zaxis_title="Elevation (m)",
        aspectmode="manual",
        aspectratio=dict(x=1, y=y_extent / x_extent, z=aspect_z),
    ),
    width=900, height=600,
)
fig.show()
Unable to display output for mime type(s): application/vnd.plotly.v1+json

Operations for Hydrological Analysis

Watershed delineation

For hydrology lovers, or lovers of the water we drink: we can think of a watershed as the whole contributing area whose water, in the hydrological cycle, flows through a given point, the outlet (pour point). The final outlet of a watershed is in most cases the sea, but placing the outlet at different locations delineates different watersheds.

The classic terrain hydrology pipeline is always similar:

  1. Fill depressions: DEMs always have spurious sinks (noise/measurement errors) that trap the water flow in an infinite loop. We need to “fill” these holes before continuing.
  2. Flow direction: for each pixel, which of its 8 neighbors would the water flow to (the neighbor with the steepest drop in altitude)? This is the D8 method.
  3. Flow accumulation: for each pixel, how many “upstream” pixels drain into it? Pixels with high flow accumulation are, by definition, where the rivers are.
  4. Watershed delineation: starting from an outlet, we “walk upstream” following the flow directions and mark the whole area that contributes to that point.

We’ll use pysheds, the most widely used Python library specifically for this.

Code
# pysheds still uses `np.in1d`, which was removed in numpy 2.x (it became `np.isin`).
# this "patch" fixes the incompatibility without changing the numpy version.
if not hasattr(np, "in1d"):
    np.in1d = np.isin

from pysheds.grid import Grid

pysheds reads from a raster file on disk (not from an in-memory array), so we’ll export dem_utm (the same kind of export we’ve done before) and load it from there.

Code
output_dir = "outputs"
os.makedirs(output_dir, exist_ok=True)
dem_utm_path = os.path.join(output_dir, "cubatao_dem_utm.tif")
dem_utm.rio.to_raster(dem_utm_path)

grid = Grid.from_raster(dem_utm_path)
dem_grid = grid.read_raster(dem_utm_path)
print("grid shape:", grid.shape, "| crs:", grid.crs.srs if hasattr(grid.crs, "srs") else grid.crs)
grid shape: (1349, 2284) | crs: PROJCS["WGS 84 / UTM zone 23S",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-45],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",10000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32723"]]

Conditioning the DEM and computing flow direction/accumulation

Code
# 1. fill holes and isolated "pits"
pit_filled_dem = grid.fill_pits(dem_grid)
flooded_dem = grid.fill_depressions(pit_filled_dem)
inflated_dem = grid.resolve_flats(flooded_dem)

# 2. flow direction (D8: 8 possible directions per pixel)
dirmap = (64, 128, 1, 2, 4, 8, 16, 32)
fdir = grid.flowdir(inflated_dem, dirmap=dirmap)

# 3. flow accumulation
acc = grid.accumulation(fdir, dirmap=dirmap)

fig, ax = plt.subplots(figsize=(10, 6))
im = ax.imshow(np.log1p(acc), cmap="cubehelix")
fig.colorbar(im, ax=ax, label="log(1 + flow accumulation)")
ax.set_title("Flow accumulation")
ax.axis("off")
plt.show()

Choosing an outlet and delineating the watershed

We need to pick an outlet to “cut” the watershed. To make sure we land on a real river (and not in the middle of a hill), we’ll use the pixel with the highest flow accumulation in our whole area: by definition, more water passes there than anywhere else in our grid.

In a real application you would usually choose this point by hand (e.g. where a stream gauge is, or the mouth of a specific river) and use grid.snap_to_mask to “snap” the chosen coordinates to the nearest river pixel.

Code
row_pour, col_pour = np.unravel_index(np.argmax(acc), acc.shape)
x_pour, y_pour = grid.affine * (col_pour, row_pour)
print(f"Chosen outlet: ({x_pour:.0f}, {y_pour:.0f}) | flow accumulation: {acc.max():.0f} pixels")

catchment = grid.catchment(x=x_pour, y=y_pour, fdir=fdir, dirmap=dirmap, xytype="coordinate")

cellsize = abs(grid.affine[0])
area_km2 = catchment.sum() * (cellsize ** 2) / 1e6
print(f"Watershed area: {area_km2:.1f} km²  ({catchment.sum()} pixels)")
# notice: the number of pixels in the watershed is EXACTLY the flow accumulation at the outlet —
# that's no coincidence, it's the very definition of flow accumulation!

fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(dem_utm, cmap="terrain", alpha=0.6)
ax.imshow(np.where(catchment, 1, np.nan), cmap="Blues", alpha=0.5)
ax.scatter([col_pour], [row_pour], color="red", marker="v", s=80, label="Outlet")
ax.set_title(f"Delineated watershed — {area_km2:.1f} km²")
ax.legend()
ax.axis("off")
plt.show()
Ponto de saída escolhido: (350235, 7344724) | fluxo acumulado: 961366 pixels
Área da bacia: 800.2 km²  (961366 pixels)

Vectorizing the watershed and extracting the river network

Finally, two vector products from this analysis:

  1. The watershed polygon (grid.polygonize()), turned into a GeoDataFrame, just like we did with the contour lines;
  2. The drainage network (the rivers), extracted directly from the DEM using a flow accumulation threshold. We also tried to pull hydrography from OpenStreetMap (via osmnx) for comparison, but the Overpass server wasn’t reachable from here, so we stuck with the network derived from the DEM itself, which is already a legitimate source of hydrographic data (it’s basically how products like HydroSHEDS are generated). We could try to pull the network from ANA (Brazil’s National Water Agency), but there is no Python library to do that automatically yet (THERE’S A TIP FOR A GREAT FINAL PROJECT)

While researching, I found a somewhat outdated GitHub repo that does more or less this: HydroBR. This tool is interesting too, look at how the data is made available: RainData, which comes from this paper: A Computational Platform for Exploring Brazilian Rainfall Data

Code
from shapely.geometry import shape as shapely_shape

# 1. watershed as a polygon
shapes = list(grid.polygonize(data=catchment.astype("int32"), mask=catchment))
bacia_gdf = gpd.GeoDataFrame(
    geometry=[shapely_shape(geom) for geom, _ in shapes],
    crs=grid.crs,
)
print(f"Watershed: {len(bacia_gdf)} polygon(s), area = {bacia_gdf.geometry.area.sum() / 1e6:.1f} km²")

# 2. river network: any pixel with flow accumulation above a threshold becomes a "river"
limiar_rio = 500  # in number of contributing pixels (500 px * ~28x28m ≈ 0.4 km² of catchment area)
branches = grid.extract_river_network(fdir, acc > limiar_rio, dirmap=dirmap)

rios_gdf = gpd.GeoDataFrame.from_features(branches["features"], crs=grid.crs)
print(f"River network: {len(rios_gdf)} segments")

fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(dem_utm, cmap="Greys_r", alpha=0.5,
          extent=[dem_utm.x.min(), dem_utm.x.max(), dem_utm.y.min(), dem_utm.y.max()])
bacia_gdf.boundary.plot(ax=ax, color="red", linewidth=1.5, label="Watershed boundary")
rios_gdf.plot(ax=ax, color="blue", linewidth=0.8, label="Drainage network")
ax.set_title("Delineated watershed + river network extracted from the DEM")
ax.legend()
plt.show()
Bacia: 12 polígono(s), área = 800.2 km²
Rede de rios: 2610 trechos

Bonus!

What if we combine different rasters we can access through STAC and turn them into different kinds of data for interactive visualizations?

In this next example, we use Sentinel-2 data together with DEM data to generate a point cloud. Point clouds are a “new” kind of data that has gained a lot of traction in recent years with advances in technologies such as LiDAR. Basically, these sensors cast thousands of points onto the environment being measured, and they are the gold standard for many kinds of analysis, such as biomass estimation; autonomous cars and robots use this data for navigation.

So when we merge Sentinel-2 data with digital elevation models, we can interpolate and ‘artificially’ reproduce this point cloud to create powerful visualizations.

Curious? Take a look at this repo, which teaches you how to do it.

alt text