The postgis_raster extension stores gridded data, such as elevation models, satellite indices and modelled pollution surfaces, in a raster column, cut into tiles that are found through a spatial index. Raster and vector data then meet in one SQL query: sample a raster at monitoring sites, clip it to a county, or summarize it within zones. This notebook builds a Sentinel-2 NDVI image of Syracuse, NY with geolattice.rsense (the PyRSense tools in GeoLattice), stores it in the database in two ways (in-db and out-db), and links it to Atlas health and environment layers.
Learning objectives
Load rasters in-db and out-db, and write and check cloud-optimized GeoTIFFs (COGs).
Inspect rasters with ST_MetaData, ST_BandMetaData and raster_columns.
Sample, clip and summarize with ST_Value, ST_Clip, ST_SummaryStats and ST_Histogram.
Compute zonal statistics in SQL and with geolatticedb, and check them against NumPy.
Run map algebra in the database (ST_MapAlgebra) and turn raster classes into polygons (ST_DumpAsPolygons).
Data
Data
Source
Use
Sentinel-2 L2A, tile 18TVN, 2 Aug 2025 (red, NIR, scene classification), Syracuse AOI
US county boundaries, EPA PM2.5 monitors, Superfund sites
USA Health Data Atlas
Zones and points
Contents
Setup
A PyRSense output: Sentinel-2 NDVI as a COG
In-db vs. out-db rasters
Raster metadata
ST_Value, ST_Clip and ST_SummaryStats
Zonal statistics and raster/vector integration
Map algebra and raster to polygons
Exporting rasters
Summary and exercises
Setup
Installation. This notebook needs installation option 6 (every GeoLattice module): pip install "geolattice[all]". See “Installation options” in the GeoLattice README.
Code
import warnings # warning controlwarnings.filterwarnings("ignore", category=UserWarning) # hide routine library warningswarnings.filterwarnings("ignore", category=RuntimeWarning) # all-NaN windowsimport shutil # find programsimport subprocess # run raster2pgsqlimport time # timingimport numpy as np # arraysimport pandas as pd # tablesimport geopandas as gpd # vector dataimport xarray as xr # labelled rastersimport rasterio # raster I/Ofrom rasterio.mask import mask as rio_mask # zonal check in NumPyimport psycopg # PostgreSQL driverimport matplotlib.pyplot as plt # figuresimport geolattice.rsense as rs # GeoLattice remote sensing tools (PyRSense)from geolattice import geolatticedb as pdb # GeoLattice spatial database toolsrasterio.Env(CPL_LOG="/dev/null").__enter__() # quiet GDAL messagesplt.rcParams.update({"figure.dpi": 110}) # figure resolution
Code
import os # environment variablesimport json # JSON parsingimport urllib.request # download files over HTTPfrom pathlib import Path # file paths# The GeoLattice repository root: the first folder above this notebook that holds data/ and Tutorials/HERE = Path.cwd() # folder of this notebookROOT =next(p for p in [HERE, *HERE.parents] if (p /"Data").is_dir() and (p /"Tutorials").is_dir())GEOLATTICE_DATA = ROOT /"Data"# shared GeoLattice data folderDATA = ROOT /"Data"/"06_spatialDB"# data folder of this moduleOUT = DATA /"outputs"/"06_03_01"# outputs written by this notebookOUT.mkdir(parents=True, exist_ok=True) # create it if needed# USA Health Data Atlas (https://zia207.github.io/USA-Health-Data-Atlas/): raw files on GitHubATLAS ="https://raw.githubusercontent.com/zia207/USA-Health-Data-Atlas/main"def fetch(rel, base=ATLAS, folder="atlas"): # download helper"""Download a file once (default: from the Atlas repository) and return its local path.""" path = DATA / folder / rel # local cache pathifnot path.exists(): # download only if missing path.parent.mkdir(parents=True, exist_ok=True) # create the cache folderprint(f"Downloading {rel} ...") # progress message urllib.request.urlretrieve(f"{base}/{rel}", path) # copy the URL to the local pathreturn path # the local pathdef atlas_js(rel): # read an Atlas data file"""Atlas data files are JavaScript (`window.X = {...};`); return the JSON object inside.""" text = fetch(rel).read_text(encoding="utf-8") # whole file as textreturn json.loads(text[text.index("=") +1:].strip().rstrip(";")) # strip the assignment and parsedef atlas_counties(): # county polygons of the Atlas"""US county polygons (Census cartographic boundaries, EPSG:4326) with a 5-digit FIPS code.""" g = gpd.read_file(fetch("assets/geojson_counties_fips.json")) # GeoJSON from the Atlas g["fips"] = g["STATE"] + g["COUNTY"] # state + county code = FIPS g = g.rename(columns={"NAME": "name", "STATE": "statefp", "CENSUSAREA": "census_sqmi"}) # tidy namesreturn g[["fips", "statefp", "name", "census_sqmi", "geometry"]].set_crs(4326, allow_override=True)def superfund_sites(): # EPA Superfund National Priorities List sites from the Atlas"""Superfund NPL sites as points (EPSG:4326).""" s = pd.DataFrame(atlas_js("assets/superfund_npl_data.js")["sites"]) # one row per site s = s.dropna(subset=["lat", "lon"]) # keep sites with coordinates s = s[["epa_id", "name", "status", "state", "city", "county", "score", "listed", "lat", "lon"]] # main fieldsreturn gpd.GeoDataFrame(s, geometry=gpd.points_from_xy(s.lon, s.lat), crs=4326) # points# PostGIS connection string (see 06_01_02 for the Docker container); override with GEOLATTICE_PG_DSNPG_DSN = os.environ.get("GEOLATTICE_PG_DSN", "postgresql://postgres:geolattice@localhost:5432/geolattice")print("Repository:", ROOT) # where the data are read from# Folder of DATA as the database server sees it (out-db rasters are read by the server).# Local server: the same path. Docker (06_01_02 compose file): the Data folder is mounted at /data.SERVER_DATA = Path(os.environ.get("GEOLATTICE_SERVER_DATA", str(DATA)))
Repository: /home/zia207/Github/GeoLattice
Code
pg = pdb.connect("postgis", dsn=PG_DSN) # PostGIS through geolatticedbq = pg.query # SQL -> GeoDataFrame / DataFramepg.execute("CREATE EXTENSION IF NOT EXISTS postgis_raster") # raster type and functions# out-db rasters and COG access must be switched on (per database; new connections pick it up)pg.execute("ALTER DATABASE "+ psycopg.conninfo.conninfo_to_dict(PG_DSN)["dbname"] +" SET postgis.enable_outdb_rasters = true")pg.execute("ALTER DATABASE "+ psycopg.conninfo.conninfo_to_dict(PG_DSN)["dbname"] +" SET postgis.gdal_enabled_drivers = 'GTiff'")pg.close(); pg = pdb.connect("postgis", dsn=PG_DSN); q = pg.query # reconnect with the new settingsprint(q("SHOW postgis.enable_outdb_rasters").iloc[0, 0], q("SHOW postgis.gdal_enabled_drivers").iloc[0, 0])def tool(*args): # run raster2pgsql and return its SQLif shutil.which(args[0]) isNone:raiseFileNotFoundError(f"{args[0]} not found: install PostGIS client tools or use docker exec")return subprocess.run([str(a) for a in args], capture_output=True, text=True, check=True).stdoutcounties = atlas_counties() # Atlas countiessites = superfund_sites() # Superfund sitesaq = pd.DataFrame(atlas_js("assets/air_quality_data.js")["sites"]) # EPA monitors (all pollutants)aq = aq.dropna(subset=["lat", "lon"]).drop_duplicates("id") # one row per monitoring sitemonitors = gpd.GeoDataFrame(aq[["id", "n", "st", "p"]].set_axis(["site_id", "name", "state", "pollutant"], axis=1), geometry=gpd.points_from_xy(aq.lon, aq.lat), crs=4326) # pointspg.load(counties[counties.statefp =="36"], "ny_counties"); pg.load(sites, "superfund"); pg.load(monitors, "aq_sites")
true GTiff
'aq_sites'
A GeoLattice output: Sentinel-2 NDVI as a COG
The red (B04) and near-infrared (B08) bands are 10 m Sentinel-2 L2A surface reflectance stored as integers. The STAC item gives the conversion (raster:bands scale 0.0001 and offset -0.1 for processing baseline 05.11), but also records earthsearch:boa_offset_applied = true: Earth Search already removed the offset, so applying it again would push dark surfaces below zero. The code reads both fields. The scene classification layer (SCL, 20 m) flags clouds, cloud shadows and water. We compute the Normalized Difference Vegetation Index, NDVI = (NIR - red) / (NIR + red), with geolattice.rsense, mask clouds, shadows and water (so that greenness is compared over land only), and write the result as a cloud-optimized GeoTIFF: tiled, compressed and with overviews, so that programs can read just the part and resolution they need.
Code
S2 = GEOLATTICE_DATA /"00_shared"/"data_web_cloud_gis"/"s2_syracuse_2025"/"S2C_18TVN_20250802_0_L2A"# one sceneitem = json.load(open(S2 /"item.json")) # STAC item of the scenerb = item["assets"]["red"]["raster:bands"][0] # scale and offset of the bandoffset =0.0if item["properties"].get("earthsearch:boa_offset_applied") else rb.get("offset", 0.0) # avoid double offsetprint(f"scale {rb['scale']}, offset {rb['offset']} (already applied: {offset ==0.0})")ds = xr.Dataset({b: rs.read(S2 /f"{b}.tif").squeeze("band", drop=True) for b in ["red", "nir"]}) # 10 m bandsds = (ds.where(ds >0) * rb["scale"] + offset).clip(min=0) # DN -> surface reflectance (0 = nodata)ds = ds.rio.write_crs(32618) # UTM zone 18Nscl = rs.read(S2 /"scl.tif").squeeze("band", drop=True).rio.reproject_match(ds["red"], resampling=0) # 20 m -> 10 mbad = scl.isin([0, 1, 3, 6, 8, 9, 10]) # no data, saturated, cloud shadow, water, clouds, cirrusndvi = rs.optical.index(ds, "NDVI").where(~bad).astype("float32") # NDVI with clouds maskedndvi = ndvi.rio.write_crs(32618).rio.write_nodata(np.nan)cog = OUT /"ndvi_syracuse_20250802_cog.tif"# the COG filers.write(ndvi, cog, cog=True) # cloud-optimized GeoTIFF (geolattice.rsense)print(f"NDVI {ndvi.shape[0]} x {ndvi.shape[1]} cells at 10 m; masked (cloud, shadow, water) {float(bad.mean()):.1%}; "f"mean {float(ndvi.mean()):.2f}; file {cog.stat().st_size /1e6:.1f} MB")with rasterio.open(cog) as src: # check the COG structureprint("tiled:", src.profile.get("tiled"), "| block:", src.block_shapes[0], "| overviews:", src.overviews(1),"| compression:", src.compression)
scale 0.0001, offset -0.1 (already applied: True)
NDVI 1354 x 1485 cells at 10 m; masked (cloud, shadow, water) 4.0%; mean 0.57; file 8.9 MB
tiled: True | block: (512, 512) | overviews: [2, 4] | compression: Compression.deflate
Code
fig, ax = plt.subplots(figsize=(8, 7)) # one mapndvi.plot(ax=ax, cmap="RdYlGn", vmin=-0.2, vmax=0.9, cbar_kwargs={"label": "NDVI"}) # the indexax.set_title("Sentinel-2 NDVI, Syracuse NY, 2 Aug 2025 (geolattice.rsense)"); ax.set_axis_off(); plt.show()
Downtown Syracuse, the highway corridors and the commercial and industrial land along the shore of Onondaga Lake and in the south-east have low NDVI (orange), while parks, cemeteries and the wooded hills in the south are green. Onondaga Lake (north-west corner) is masked as water. The scene has almost no cloud, so 4% of the cells are masked, nearly all of them water.
In-db vs. out-db rasters
In-db
Out-db (raster2pgsql -R)
Pixels stored
inside the table (TOAST pages)
in the original file; the table holds tile footprints, metadata and the file path
Load time and table size
slower, larger
fast, tiny
Backups (pg_dump)
include the pixels
include only the paths; the files must be backed up separately
Requirements
none
the server must be able to read the file path; postgis.enable_outdb_rasters = true
Best for
data edited or analyzed often in SQL
large archives (satellite scenes, COGs) read occasionally
Out-db works well with COGs, because each tile reads just its block of the file, and GDAL can read COGs from object storage (/vsis3/, /vsicurl/) when the server is allowed to. We load the NDVI COG both ways:
Code
rows = [] # one row per storage modefor mode in ["in-db", "out-db"]: table ="ndvi_indb"if mode =="in-db"else"ndvi_outdb" pg.execute(f"DROP TABLE IF EXISTS {table}") path = cog if mode =="in-db"else SERVER_DATA / cog.relative_to(DATA) # out-db: path as the server sees it args = ["raster2pgsql", "-s", "32618", "-t", "256x256", "-I", "-C", "-F"] + (["-R"] if mode =="out-db"else []) t0 = time.perf_counter() pg.execute(tool(*args, path, f"public.{table}")) # generate and run the SQL t_load = time.perf_counter() - t0 size = q(f"SELECT pg_total_relation_size('{table}') / 1e6 AS mb").mb.iloc[0] # table + TOAST + index t0 = time.perf_counter() stats = q(f"SELECT (ST_SummaryStatsAgg(rast, 1, true)).* FROM {table}") # read every pixel once rows.append({"storage": mode, "tiles": q(f"SELECT count(*) FROM {table}").iloc[0, 0], "load s": t_load,"table MB": float(size), "full scan s": time.perf_counter() - t0,"mean NDVI": float(stats["mean"].iloc[0])})pd.DataFrame(rows).set_index("storage").round(3) # compare
tiles
load s
table MB
full scan s
mean NDVI
storage
in-db
36
0.416
8.290
0.068
0.574
out-db
36
0.138
0.074
0.158
0.574
The out-db table is a small fraction of the in-db size, because it holds only tile footprints and the path, and both return the same statistics. A full scan of the out-db raster is slower because each tile is read from the file through GDAL. For repeated pixel-level analysis keep rasters in-db; for large archives keep the COGs as files (or in object storage) and register them out-db. In a Docker setup the path written by -R must be the path inside the container, which is why the notebook uses SERVER_DATA (/data with the compose file from 06_01_02).
The Onondaga County DEM goes in-db with geolatticedb, which calls raster2pgsql with tiling, constraints and an index:
Code
pg.raster.load(GEOLATTICE_DATA /"00_shared"/"raster_data"/"USA"/"Onondaga_DEM.tif", "ono_dem", srid=4326, tile_size=100)pg.raster.info("ono_dem") # metadata from raster_columns
r_raster_column
srid
scale_x
scale_y
blocksize_x
blocksize_y
num_bands
pixel_types
nodata_values
out_db
0
rast
4326
0.001133
-0.001133
100
100
1
[32BF]
[-3.4028230607371e+38]
[False]
Raster metadata
ST_MetaData returns the georeference of a tile (upper-left corner, size, scale, skew, SRID, number of bands) and ST_BandMetaData the pixel type, nodata value and, for out-db bands, the file path. ST_Envelope and ST_ConvexHull give the footprint as a geometry.
Code
q("""SELECT 'in-db' AS storage, (md).upperleftx, (md).upperlefty, (md).width, (md).height, (md).scalex, (md).srid, (bm).pixeltype, (bm).nodatavalue, (bm).isoutdb, right((bm).path, 45) AS pathFROM (SELECT ST_MetaData(rast) AS md, ST_BandMetaData(rast, 1) AS bm FROM ndvi_indb LIMIT 1) tUNION ALLSELECT 'out-db', (md).upperleftx, (md).upperlefty, (md).width, (md).height, (md).scalex, (md).srid, (bm).pixeltype, (bm).nodatavalue, (bm).isoutdb, right((bm).path, 45)FROM (SELECT ST_MetaData(rast) AS md, ST_BandMetaData(rast, 1) AS bm FROM ndvi_outdb LIMIT 1) t""")
storage
upperleftx
upperlefty
width
height
scalex
srid
pixeltype
nodatavalue
isoutdb
path
0
in-db
400520.0
4772650.0
256
256
10.0
32618
32BF
NaN
False
NaN
1
out-db
400520.0
4772650.0
256
256
10.0
32618
32BF
NaN
True
tputs/06_03_01/ndvi_syracuse_20250802_cog.tif
Code
tiles = q("SELECT rid, ST_Envelope(rast) AS geom, (ST_SummaryStats(rast)).mean AS mean_ndvi FROM ndvi_indb")ax = tiles.plot("mean_ndvi", cmap="RdYlGn", edgecolor="k", lw=0.4, figsize=(7, 6), legend=True, vmin=0, vmax=0.8, legend_kwds={"label": "tile mean NDVI"}) # tile footprints coloured by their meanax.set_title(f"{len(tiles)} tiles of 256 x 256 cells (one row each)"); ax.set_axis_off(); plt.show()
ST_Value, ST_Clip and ST_SummaryStats
Function
Returns
ST_Value(rast, band, point)
the cell value under a point (resample => 'bilinear' for interpolation)
ST_Clip(rast, band, geom, crop)
the part of a raster inside a geometry, as a raster
ST_SummaryStats(rast) / ST_SummaryStatsAgg
count, sum, mean, stddev, min, max of a tile / of many tiles
ST_Histogram, ST_Quantile, ST_ValueCount
distributions and class counts
NDVI and elevation at the EPA air quality monitoring sites and Superfund sites that fall inside the scene (one of each: the East Syracuse PM2.5 site and the Onondaga Lake site). The points are in EPSG:4326 and the NDVI in UTM 18N, so the points are transformed to the raster SRID; the spatial join ST_Intersects(rast, geom) finds the tile under each point through the GiST index:
Code
pts = q("""WITH p AS ( SELECT 'EPA monitor (' || pollutant || ')' AS kind, name, geom FROM aq_sites UNION ALL SELECT 'Superfund site', name, geom FROM superfund)SELECT p.kind, p.name, round(ST_Value(n.rast, 1, ST_Transform(p.geom, 32618))::numeric, 3) AS ndvi, round(ST_Value(d.rast, 1, p.geom)::numeric) AS elevation_m, p.geomFROM pJOIN ndvi_indb n ON ST_Intersects(n.rast, ST_Transform(p.geom, 32618)) -- tile under the pointLEFT JOIN ono_dem d ON ST_Intersects(d.rast, p.geom)""")pts.drop(columns="geom") # sites inside the NDVI scene
kind
name
ndvi
elevation_m
0
Superfund site
Onondaga Lake
0.424
114
1
EPA monitor (PM25)
EAST SYRACUSE
0.646
128
Point values are noisy: a monitor on a rooftop or beside a parking lot reads the NDVI of one 10 m cell. Exposure studies therefore summarize the raster in a buffer around each site. ST_Clip cuts the raster to a 500 m circle and ST_SummaryStats summarizes it:
Code
buf = q("""WITH p AS (SELECT name, ST_Buffer(ST_Transform(geom, 32618), 500) AS zone FROM aq_sites WHERE ST_Intersects(ST_Transform(geom, 32618), (SELECT ST_Union(ST_Envelope(rast)) FROM ndvi_indb)))SELECT p.name, (ST_SummaryStatsAgg(ST_Clip(n.rast, 1, p.zone, true), 1, true)).*, (SELECT count(*) FROM ndvi_indb) AS tiles_totalFROM p JOIN ndvi_indb n ON ST_Intersects(n.rast, p.zone) GROUP BY p.name""")buf[["name", "count", "mean", "stddev", "min", "max"]].round(3) # NDVI within 500 m of each monitoring site
name
count
mean
stddev
min
max
0
EAST SYRACUSE
7805
0.49
0.229
0.001
0.842
Code
hist = q("""SELECT (h).min, (h).max, (h).count FROM ( SELECT ST_Histogram(ST_Union(rast), 1, true, 20, false) AS h FROM ndvi_indb) t""") # 20 bins, whole scenefig, ax = plt.subplots(figsize=(8, 3.2)) # one histogramax.bar((hist["min"] + hist["max"]) /2, hist["count"], width=hist["max"] - hist["min"], color="#41ab5d", edgecolor="w")ax.set(xlabel="NDVI", ylabel="cells", title="ST_Histogram of the Syracuse NDVI"); plt.show()
Zonal statistics and raster/vector integration
Zonal statistics summarize a raster within each polygon of a vector layer. In SQL the pattern is: join tiles to zones with ST_Intersects, clip each tile to its zone with ST_Clip, and aggregate with ST_SummaryStatsAgg per zone. geolatticedb.raster.zonal_stats writes that query (and reprojects the zones to the raster SRID). We use 250 m hexagons over the Syracuse scene as zones, then check the result against a NumPy calculation with rasterio.mask.
Code
pg.execute("""DROP TABLE IF EXISTS syr_hex;CREATE TABLE syr_hex ASSELECT row_number() OVER () AS hex_id, ST_Transform(h.geom, 4326) AS geomFROM ST_HexagonGrid(250, (SELECT ST_Union(ST_Envelope(rast)) FROM ndvi_indb)) hWHERE ST_Within(h.geom, (SELECT ST_Union(ST_Envelope(rast)) FROM ndvi_indb));CREATE INDEX ON syr_hex USING GIST (geom)""") # hexagons inside the scenet0 = time.perf_counter()zs = pg.raster.zonal_stats("ndvi_indb", "syr_hex", stats=["count", "mean", "min", "max"]) # geolatticedbprint(f"{len(zs):,} hexagons, zonal statistics in {time.perf_counter() - t0:.1f} s")check = zs.sample(25, random_state=1) # verify 25 hexagons with rasterio + NumPywith rasterio.open(cog) as src: np_mean = [float(np.nanmean(rio_mask(src, [g], crop=True, nodata=np.nan, all_touched=False)[0]))for g in check.to_crs(32618).geometry]print("max |PostGIS - NumPy| mean NDVI:", round(float(np.nanmax(np.abs(np.array(np_mean) - check["mean"]))), 6))
1,140 hexagons, zonal statistics in 0.4 s
max |PostGIS - NumPy| mean NDVI: 0.0
Both methods count the cells whose centre falls inside each hexagon, so they agree to floating-point precision. A second integration step joins the raster summary to vector layers. Here we flag hexagons that contain an EPA monitoring site or lie within 2 km of a Superfund site, and compare their greenness:
Code
pg.load(zs, "syr_hex_ndvi") # the zonal result as a tablecmp= q("""SELECT CASE WHEN EXISTS (SELECT 1 FROM superfund s WHERE ST_DWithin(h.geom::geography, s.geom::geography, 2000)) THEN 'within 2 km of a Superfund site' ELSE 'farther' END AS zone, count(*) AS hexagons, round(avg(mean)::numeric, 3) AS mean_ndvi, round(avg((mean < 0.3)::int)::numeric, 3) AS share_low_greenFROM syr_hex_ndvi h WHERE count > 400 GROUP BY 1""")fig, ax = plt.subplots(figsize=(8, 7)) # map of the hexagonszs.plot("mean", ax=ax, cmap="RdYlGn", vmin=0, vmax=0.8, legend=True, legend_kwds={"label": "mean NDVI per hexagon"})q("SELECT geom FROM superfund").clip(zs.total_bounds).plot(ax=ax, color="k", marker="X", markersize=60, label="Superfund")q("SELECT geom FROM aq_sites").clip(zs.total_bounds).plot(ax=ax, color="blue", markersize=30, label="EPA monitor")ax.legend(loc="lower left"); ax.set_title("Mean NDVI in 250 m hexagons, Syracuse"); ax.set_axis_off(); plt.show()cmp# greenness near and far from Superfund sites
zone
hexagons
mean_ndvi
share_low_green
0
farther
1054
0.572
0.055
1
within 2 km of a Superfund site
46
0.484
0.196
The only Superfund site in this scene is Onondaga Lake, recorded at a point on its south-western shore. With the lake masked, the land hexagons within 2 km of that point have a lower mean NDVI (0.48 against 0.57 elsewhere) and are about four times as often below NDVI 0.3 (20% against 6%). That shore is mostly industrial and highway land. This describes land cover, not exposure or health; it shows how a raster summary becomes an ordinary attribute that joins to sites, monitors, tracts or health outcomes.
Map algebra and raster to polygons
ST_MapAlgebra computes new pixel values from one or more bands with an expression, inside the database. We load the red and NIR bands as a two-band raster, compute NDVI in SQL and compare it with the geolattice.rsense result. ST_Reclass and ST_DumpAsPolygons then turn a class of the raster into vector polygons, here green space with NDVI of at least 0.6.
Code
two_band = OUT /"red_nir_reflectance.tif"# red and NIR reflectance as one 2-band GeoTIFFrs.write(ds[["red", "nir"]].to_array("band").astype("float32").rio.write_nodata(np.nan), two_band, cog=False)pg.execute("DROP TABLE IF EXISTS s2_rednir")pg.execute(tool("raster2pgsql", "-s", "32618", "-t", "256x256", "-I", "-C", two_band, "public.s2_rednir"))t0 = time.perf_counter()pg.execute("""DROP TABLE IF EXISTS ndvi_sql;CREATE TABLE ndvi_sql ASSELECT rid, ST_MapAlgebra(rast, 1, rast, 2, -- band 1 = red, band 2 = NIR 'CASE WHEN [rast1] + [rast2] > 0 THEN ([rast2] - [rast1]) / ([rast2] + [rast1]) END', '32BF') AS rastFROM s2_rednir""")print(f"ST_MapAlgebra NDVI in {time.perf_counter() - t0:.1f} s")sql_vs_py = q("""SELECT (ST_SummaryStatsAgg(rast, 1, true)).mean AS sql_mean FROM ndvi_sql""").iloc[0, 0]print(f"mean NDVI, SQL map algebra (no cloud mask): {sql_vs_py:.4f} | geolattice.rsense without mask: "f"{float(rs.optical.index(ds, 'NDVI').mean()):.4f}")
ST_MapAlgebra NDVI in 3.0 s
mean NDVI, SQL map algebra (no cloud mask): 0.5545 | geolattice.rsense without mask: 0.5545
Code
green = q("""SELECT (dp).val AS class, ST_Transform((dp).geom, 4326) AS geom, ST_Area((dp).geom) AS area_m2FROM (SELECT ST_DumpAsPolygons(ST_Reclass(rast, 1, '[-1-0.6):0, [0.6-1]:1', '8BUI', 0)) AS dp FROM ndvi_indb) tWHERE (dp).val = 1 -- green space only""")green_union = q("""SELECT ST_Transform(ST_Union((dp).geom), 4326) AS geom FROM ( SELECT ST_DumpAsPolygons(ST_Reclass(rast, 1, '[-1-0.6):0, [0.6-1]:1', '8BUI', 0)) AS dp FROM ndvi_indb) tWHERE (dp).val = 1""") # merged across tile edgesprint(f"{len(green):,} polygon pieces from {len(tiles)} tiles; green space (NDVI >= 0.6): "f"{green.area_m2.sum() /1e6:.1f} km² of {ndvi.count().item() *100/1e6:.1f} km² observed")ax = green_union.plot(color="#238b45", figsize=(8, 7)) # green space polygonsax.set_title("Green space (NDVI >= 0.6) as polygons from ST_DumpAsPolygons"); ax.set_axis_off(); plt.show()
11,668 polygon pieces from 36 tiles; green space (NDVI >= 0.6): 103.1 km² of 193.0 km² observed
The SQL map algebra reproduces the geolattice.rsense NDVI (both without the cloud mask). The reclassified raster became vector polygons; because each tile is vectorized separately, the pieces are merged with ST_Union to remove tile seams. The polygons can now be buffered, overlaid with parcels or tracts, or used in distance calculations like any vector layer.
Exporting rasters
ST_AsGDALRaster(rast, format) (or ST_AsTIFF, ST_AsPNG) returns a file’s bytes. Union the tiles first to export one image. The result opens in rasterio or xarray directly from memory:
Code
clip_tif = q("""SELECT ST_AsGDALRaster(ST_Clip(ST_Union(d.rast), 1, c.geom, true), 'GTiff') AS tifFROM ono_dem d, ny_counties c WHERE c.fips = '36067' AND ST_Intersects(d.rast, c.geom) GROUP BY c.geom""").tif.iloc[0] # Onondaga County DEM, clipped to the county, as GeoTIFF bytesout_tif = OUT /"onondaga_dem_clip.tif"; out_tif.write_bytes(bytes.fromhex(clip_tif) ifisinstance(clip_tif, str) elsebytes(clip_tif))dem = rs.read(out_tif).squeeze("band", drop=True) # back into xarrayfig, ax = plt.subplots(figsize=(7, 6))dem.plot(ax=ax, cmap="terrain", cbar_kwargs={"label": "elevation (m)"}) # the clipped DEMcounties[counties.fips =="36067"].boundary.plot(ax=ax, color="k", lw=0.8) # county outlineax.set_title(f"Onondaga County DEM exported from PostGIS (mean {float(dem.mean()):.0f} m)"); ax.set_axis_off(); plt.show()pg.close() # close the connection
Summary and exercises
Main points
postgis_raster stores rasters as tiles in a raster column with a GiST index on the tile footprints; raster2pgsql -t -I -C loads them.
In-db rasters are self-contained and fast to scan; out-db rasters (-R) keep pixels in the file, typically a COG, and need postgis.enable_outdb_rasters and a path the server can read.
ST_Value, ST_Clip and ST_SummaryStats(Agg) sample, cut and summarize rasters inside SQL, so raster values join to points and polygons like attributes.
Zonal statistics (geolatticedb.raster.zonal_stats, or ST_Clip + ST_SummaryStatsAgg) matched a NumPy calculation exactly.
ST_MapAlgebra computes new rasters in the database; ST_Reclass + ST_DumpAsPolygons turn raster classes into vector polygons.
ST_AsGDALRaster exports results to GeoTIFF for geolattice.rsense, rasterio or xarray.
Load the 23 July and 19 September 2025 scenes as well and compute NDVI change per hexagon in SQL.
Compare ST_Value with resample => 'bilinear' and nearest-neighbour values at the monitoring sites.
Compute the share of each hexagon covered by green space using the green_union polygons and ST_Intersection. Does it agree with the share of cells with NDVI >= 0.6?
Register a remote COG out-db with raster2pgsql -R /vsicurl/https://... and query it. Which server settings are needed?
Summarize the Onondaga DEM within 2 km hexagons and find the steepest hexagon with ST_Slope.