Source code: Defra Survey Data Download: how to download free England LiDAR (DTM, DSM and point clouds)
Runnable Python scripts, requirements and console output for the tutorial “Defra Survey Data Download: how to download free England LiDAR (DTM, DSM and…
Last updated
These are the exact scripts used to produce every figure and number in Defra Survey Data Download: how to download free England LiDAR (DTM, DSM and point clouds). Download them, install the requirements into a fresh virtual environment and run them from this folder.
python -m venv .venv.venv\Scripts\activate # macOS/Linux: source .venv/bin/activatepip install -r requirements.txtpython defra_survey_download.pydefra_survey_download.py
"""Find and download Environment Agency LiDAR tiles from Defra Survey Data Download.
Uses the same search service as the map at https://environment.data.gov.uk/survey:POST a GeoJSON polygon (WGS84 longitude/latitude) and get back every tile, product,year and resolution that intersects it. Each result has a direct zip download link.
Examples: python defra_survey_download.py --bbox -2.478 50.690 -2.460 50.698 --list python defra_survey_download.py --bbox -2.478 50.690 -2.460 50.698 \ --product lidar_composite_dtm --resolution 1 --out data
Standard library only. Data: Environment Agency, Open Government Licence v3.0."""
from __future__ import annotations
import argparseimport jsonimport sysimport urllib.requestimport zipfilefrom pathlib import Path
SEARCH_URL = "https://environment.data.gov.uk/tiles/collections/survey/search"
def search(bbox: tuple[float, float, float, float]) -> list[dict]: """Every survey product that intersects a lon/lat bounding box.""" w, s, e, n = bbox polygon = {"type": "Polygon", "coordinates": [[[w, s], [e, s], [e, n], [w, n], [w, s]]]} req = urllib.request.Request( SEARCH_URL, data=json.dumps(polygon).encode(), # The service only accepts the GeoJSON media type; plain application/json is rejected. headers={"Content-Type": "application/geo+json", "User-Agent": "technicalgis-tutorial"}, method="POST", ) with urllib.request.urlopen(req, timeout=60) as r: return json.load(r)["results"]
def download(uri: str, out_dir: Path) -> Path: """Download one tile zip (it can take a minute while the server prepares it) and unzip it.""" out_dir.mkdir(parents=True, exist_ok=True) req = urllib.request.Request(uri, headers={"User-Agent": "technicalgis-tutorial"}) with urllib.request.urlopen(req, timeout=600) as r: name = r.headers.get_filename() or uri.rstrip("/").replace("/", "-") + ".zip" path = out_dir / name with open(path, "wb") as f: while chunk := r.read(1 << 20): f.write(chunk) with zipfile.ZipFile(path) as z: z.extractall(out_dir / path.stem) names = z.namelist() print(f" {path.name}: {path.stat().st_size / 1e6:.0f} MB") for n in names: print(f" {n}") return out_dir / path.stem
def main() -> None: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--bbox", nargs=4, type=float, required=True, metavar=("WEST", "SOUTH", "EAST", "NORTH")) p.add_argument("--list", action="store_true", help="list what is available and stop") p.add_argument("--product", default="lidar_composite_dtm", help="product id, e.g. national_lidar_programme_point_cloud") p.add_argument("--year", help="survey year; default is the latest available") p.add_argument("--resolution", default="1", help="resolution in metres, e.g. 1, 2 or 0.5 (ignored for point clouds)") p.add_argument("--out", type=Path, default=Path("data")) a = p.parse_args()
results = search(tuple(a.bbox)) if a.list: print(f"{len(results)} products for this area") for r in results: print(f" {r['product']['id']:<42} {r['year']['label']} {r['resolution']['label']:<5} {r['tile']['label']}") return
picked = [r for r in results if r["product"]["id"] == a.product] if "point_cloud" not in a.product: picked = [r for r in picked if r["resolution"]["id"] == a.resolution] if not picked: sys.exit(f"No {a.product} tiles at {a.resolution} m here. Run with --list to see what there is.") year = a.year or max(r["year"]["id"] for r in picked) picked = [r for r in picked if r["year"]["id"] == year] print(f"Downloading {len(picked)} tile(s) of {picked[0]['product']['label']} {year}") for r in picked: download(r["uri"], a.out)
if __name__ == "__main__": main()hillshade_tile.py
"""Hillshade a Defra Survey Data Download DTM tile and save it as a PNG.
python hillshade_tile.py data/lidar_composite_dtm-2022-1-SY68ne/SY68ne_DTM_1m.tif \ --window 365900 87700 368100 89100 --out maiden-castle-hillshade.png
Needs rasterio, numpy and matplotlib (see requirements.txt)."""
from __future__ import annotations
import argparse
import matplotlib.pyplot as pltimport numpy as npimport rasteriofrom matplotlib.colors import LightSourcefrom rasterio.windows import from_bounds
def main() -> None: p = argparse.ArgumentParser() p.add_argument("tif") p.add_argument("--window", nargs=4, type=float, metavar=("XMIN", "YMIN", "XMAX", "YMAX"), help="British National Grid bounds to crop to (default: whole tile)") p.add_argument("--out", default="hillshade.png") a = p.parse_args()
with rasterio.open(a.tif) as src: win = from_bounds(*a.window, transform=src.transform) if a.window else None z = src.read(1, window=win, masked=True).astype("float64") print(f"CRS {src.crs}, pixel {src.res[0]:g} m, nodata {src.nodata:g}") z = z.filled(np.nan) print(f"{z.shape[1]} x {z.shape[0]} pixels, height {np.nanmin(z):.1f} to {np.nanmax(z):.1f} m above Ordnance Datum")
# Light from the north-west, exaggerated 2x so low earthworks show, over a terrain colour ramp. ls = LightSource(azdeg=315, altdeg=35) rgb = ls.shade(np.nan_to_num(z, nan=np.nanmin(z)), cmap=plt.cm.gist_earth, blend_mode="soft", vert_exag=2, dx=1, dy=1, vmin=np.nanmin(z) - 40, vmax=np.nanmax(z) + 10) plt.imsave(a.out, rgb) print(f"wrote {a.out}")
if __name__ == "__main__": main()