Datasets:
Download scripts/generate_stac.py from paeslemesa/matchgeodem: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/datasets/paeslemesa/matchgeodem/resolve/main/scripts/generate_stac.py
- Command line
-
hf download hf://datasets/paeslemesa/matchgeodem/scripts/generate_stac.py
-
curl -L -o generate_stac.py https://huggingface.co/datasets/paeslemesa/matchgeodem/resolve/main/scripts/generate_stac.py
13.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| generate_stac.py | |
| ================ | |
| Creates STAC 1.0.0 metadata for the MatchGeo-DEM dataset. | |
| Outputs: | |
| - stac/collection.json — STAC Collection for the whole dataset | |
| - stac/items/{city_id}.json — STAC Item per city (merged DEM + tile assets) | |
| Requires: rasterio, shapely (optional but recommended) | |
| Install: pip install rasterio shapely | |
| Usage: | |
| python generate_stac.py --data-root /path/to/MatchGeo-DEM-v1/data | |
| """ | |
| import json | |
| import argparse | |
| from pathlib import Path | |
| from datetime import datetime | |
| from collections import OrderedDict | |
| try: | |
| import rasterio | |
| from rasterio.crs import CRS | |
| HAS_RASTERIO = True | |
| except ImportError: | |
| HAS_RASTERIO = False | |
| try: | |
| from shapely.geometry import box, mapping | |
| HAS_SHAPELY = True | |
| except ImportError: | |
| HAS_SHAPELY = False | |
| # ------------------------------------------------------------------ | |
| # Static dataset catalog (synchronized with manifest.json) | |
| # ------------------------------------------------------------------ | |
| CITIES = [ | |
| {"id": "ATA_MV", "name": "Mount Athos, Greece", "epsg": 3031, "resolution": 2.0, "method": "satellite_insar", "n_tiles": 5625, "labelled": False, "year_start": 2011, "year_end": 2015, "provider": "Copernicus DEM"}, | |
| {"id": "BRA_SP", "name": "São Paulo, Brazil", "epsg": 31983, "resolution": 0.5, "method": "airborne_lidar", "n_tiles": 558, "labelled": True, "year_start": 2020, "year_end": 2020, "provider": "GeoSampa"}, | |
| {"id": "CHN_WS", "name": "Wutai Shan, China", "epsg": 32649, "resolution": 1.0, "method": "uav_sfm", "n_tiles": 1076, "labelled": False, "year_start": 2021, "year_end": 2021, "provider": "OpenTopography"}, | |
| {"id": "ESP_EH", "name": "El Hierro, Spain", "epsg": 3040, "resolution": 1.0, "method": "airborne_lidar", "n_tiles": 2460, "labelled": False, "year_start": 2022, "year_end": 2025, "provider": "PNOA-LiDAR"}, | |
| {"id": "FIN_LM", "name": "Lahti, Finland", "epsg": 3067, "resolution": 2.0, "method": "airborne_lidar_photogrammetry", "n_tiles": 248, "labelled": False, "year_start": 2020, "year_end": 2026, "provider": "National Land Survey of Finland"}, | |
| {"id": "GER_BN", "name": "Bonn, Germany", "epsg": 25832, "resolution": 1.0, "method": "airborne_lidar", "n_tiles": 1759, "labelled": True, "year_start": 2016, "year_end": 2018, "provider": "Geobasis NRW"}, | |
| {"id": "IDN_SV", "name": "Sinabung Volcano, Indonesia", "epsg": 32647, "resolution": 0.87, "method": "uas_sfm", "n_tiles": 181, "labelled": False, "year_start": 2018, "year_end": 2018, "provider": "OpenTopography"}, | |
| {"id": "KAZ_AC", "name": "Almaty City, Kazakhstan", "epsg": 32643, "resolution": 1.0, "method": "satellite_stereophotogrammetry", "n_tiles": 887, "labelled": False, "year_start": 2017, "year_end": 2017, "provider": "OpenTopography"}, | |
| {"id": "KSA_WA", "name": "Wadi Al-Akhdar, Saudi Arabia", "epsg": 32637, "resolution": 1.6, "method": "satellite_stereophotogrammetry", "n_tiles": 3880, "labelled": False, "year_start": 2016, "year_end": 2016, "provider": "OpenTopography"}, | |
| {"id": "NAM_HF", "name": "Hebron Fault, Namibia", "epsg": 32733, "resolution": 0.53, "method": "satellite_stereophotogrammetry", "n_tiles": 1457, "labelled": False, "year_start": 2017, "year_end": 2017, "provider": "OpenTopography"}, | |
| {"id": "NZL_KP", "name": "Kapiti Coast, New Zealand", "epsg": 2193, "resolution": 1.0, "method": "airborne_lidar", "n_tiles": 1776, "labelled": False, "year_start": 2010, "year_end": 2025, "provider": "LINZ"}, | |
| {"id": "PHL_TA", "name": "Tarlac, Philippines", "epsg": 32651, "resolution": 1.0, "method": "airborne_lidar", "n_tiles": 286, "labelled": False, "year_start": 2014, "year_end": 2017, "provider": "LiPAD"}, | |
| {"id": "USA_GC", "name": "Grand Canyon, United States", "epsg": 6341, "resolution": 10.0, "method": "lidar_ifsar", "n_tiles": 600, "labelled": False, "year_start": 2020, "year_end": 2026, "provider": "USGS 3DEP"}, | |
| ] | |
| # ------------------------------------------------------------------ | |
| # Helpers | |
| # ------------------------------------------------------------------ | |
| def read_raster_bounds(tif_path): | |
| """Return (bbox, crs_wkt, width, height) from a GeoTIFF.""" | |
| if not HAS_RASTERIO: | |
| return None, None, None, None | |
| try: | |
| with rasterio.open(tif_path) as src: | |
| bounds = src.bounds | |
| bbox = [bounds.left, bounds.bottom, bounds.right, bounds.top] | |
| return bbox, src.crs.to_wkt(), src.width, src.height | |
| except Exception as e: | |
| print(f" ⚠️ Could not read {tif_path}: {e}") | |
| return None, None, None, None | |
| def bbox_to_geometry(bbox): | |
| """Convert [minx, miny, maxx, maxy] to GeoJSON Polygon dict.""" | |
| if HAS_SHAPELY and bbox: | |
| return mapping(box(*bbox)) | |
| # Fallback manual geometry | |
| if bbox: | |
| return { | |
| "type": "Polygon", | |
| "coordinates": [[ | |
| [bbox[0], bbox[1]], [bbox[2], bbox[1]], | |
| [bbox[2], bbox[3]], [bbox[0], bbox[3]], | |
| [bbox[0], bbox[1]] | |
| ]] | |
| } | |
| return None | |
| def build_collection(data_root, output_dir): | |
| """Build the STAC Collection JSON.""" | |
| collection = OrderedDict() | |
| collection["type"] = "Collection" | |
| collection["stac_version"] = "1.0.0" | |
| collection["id"] = "matchgeo-dem-v1" | |
| collection["title"] = "MatchGeo: Multi-City DEM Dataset for Local Feature Matching" | |
| collection["description"] = ( | |
| "MatchGeo is a curated, multi-city Digital Elevation Model (DEM) dataset " | |
| "designed for training and benchmarking local feature matching algorithms " | |
| "in urban and natural terrain analysis. It aggregates high-resolution elevation " | |
| "data from 13 distinct environments across 6 continents." | |
| ) | |
| collection["license"] = "CC-BY-4.0" | |
| collection["keywords"] = [ | |
| "DEM", "DSM", "elevation", "local feature matching", | |
| "computer vision", "geospatial", "LiDAR", "photogrammetry" | |
| ] | |
| collection["providers"] = [ | |
| { | |
| "name": "Correa, S. P. L. P.; Santos, A. de Paula; Oliveira, H. N.; Beltons, D.", | |
| "roles": ["producer", "licensor"], | |
| "url": "https://doi.org/10.5281/zenodo.19339008" | |
| } | |
| ] | |
| collection["extent"] = { | |
| "spatial": {"bbox": [[-180, -90, 180, 90]]}, | |
| "temporal": { | |
| "interval": [["2011-01-01T00:00:00Z", "2026-12-31T23:59:59Z"]] | |
| } | |
| } | |
| collection["links"] = [ | |
| {"rel": "self", "href": "./collection.json", "type": "application/json"}, | |
| {"rel": "root", "href": "./collection.json", "type": "application/json"}, | |
| {"rel": "license", "href": "../LICENSE", "type": "text/plain"}, | |
| {"rel": "cite-as", "href": "https://doi.org/10.5281/zenodo.19339008", "type": "text/html"} | |
| ] | |
| # Summaries | |
| collection["summaries"] = { | |
| "gsd": [0.5, 0.53, 0.87, 1.0, 1.6, 2.0, 10.0], | |
| "eo:bands": [{"name": "elevation", "common_name": "elevation", "unit": "meter"}] | |
| } | |
| # Assets | |
| collection["assets"] = { | |
| "manifest": { | |
| "href": "../manifest.json", | |
| "type": "application/json", | |
| "title": "Central dataset manifest (JSON-LD)" | |
| }, | |
| "dataset_description": { | |
| "href": "../DATASET_DESCRIPTION.md", | |
| "type": "text/markdown", | |
| "title": "FAIR-compliant dataset description" | |
| } | |
| } | |
| out_path = output_dir / "collection.json" | |
| out_path.write_text(json.dumps(collection, indent=2), encoding="utf-8") | |
| print(f"✅ Collection written: {out_path}") | |
| return collection | |
| def build_item(city, data_root, output_dir): | |
| """Build a STAC Item for one city.""" | |
| city_id = city["id"] | |
| city_dir = Path(data_root) / city_id | |
| merged_tif = city_dir / f"{city_id}.tif" | |
| tiles_dir = city_dir / "tiles" | |
| anno_dir = city_dir / "annotations" | |
| has_annotations = anno_dir.exists() and any(anno_dir.iterdir()) | |
| # Read merged DEM bounds | |
| bbox, crs_wkt, width, height = read_raster_bounds(merged_tif) | |
| geometry = bbox_to_geometry(bbox) | |
| # Date handling | |
| year_start = city.get("year_start", 2020) | |
| year_end = city.get("year_end", 2020) | |
| dt_start = f"{year_start}-01-01T00:00:00Z" | |
| dt_end = f"{year_end}-12-31T23:59:59Z" | |
| item = OrderedDict() | |
| item["type"] = "Feature" | |
| item["stac_version"] = "1.0.0" | |
| item["id"] = city_id | |
| item["collection"] = "matchgeo-dem-v1" | |
| item["bbox"] = bbox if bbox else [-180, -90, 180, 90] | |
| item["geometry"] = geometry if geometry else {"type": "Polygon", "coordinates": [[]]} | |
| item["properties"] = { | |
| "title": city["name"], | |
| "description": f"{city['name']} — {city['method']} at {city['resolution']} m resolution", | |
| "datetime": dt_start, | |
| "start_datetime": dt_start, | |
| "end_datetime": dt_end, | |
| "providers": [{"name": city["provider"], "roles": ["producer"]}], | |
| "gsd": city["resolution"], | |
| "proj:epsg": city["epsg"], | |
| "matchgeo:method": city["method"], | |
| "matchgeo:n_tiles": city["n_tiles"], | |
| "matchgeo:labelled": city["labelled"], | |
| "matchgeo:has_annotations": has_annotations, | |
| } | |
| if crs_wkt: | |
| item["properties"]["proj:wkt2"] = crs_wkt | |
| # Assets | |
| item["assets"] = {} | |
| if merged_tif.exists(): | |
| item["assets"]["dem"] = { | |
| "href": str(merged_tif.relative_to(Path(data_root).parent)), | |
| "type": "image/tiff; application=geotiff; profile=cloud-optimized", | |
| "title": f"Merged DEM — {city_id}", | |
| "roles": ["data"], | |
| "eo:bands": [{"name": "elevation", "common_name": "elevation", "unit": "meter"}] | |
| } | |
| if tiles_dir.exists(): | |
| item["assets"]["tiles"] = { | |
| "href": str(tiles_dir.relative_to(Path(data_root).parent)) + "/", | |
| "type": "application/x-geotiff-tiles", | |
| "title": f"333×333 pixel tiles — {city_id}", | |
| "roles": ["data"], | |
| "x-asset-count": city["n_tiles"] | |
| } | |
| extent_geojson = city_dir / f"{city_id}_extent.geojson" | |
| if extent_geojson.exists(): | |
| item["assets"]["extent"] = { | |
| "href": str(extent_geojson.relative_to(Path(data_root).parent)), | |
| "type": "application/geo+json", | |
| "title": "Coverage extent polygon", | |
| "roles": ["metadata"] | |
| } | |
| tiles_geojson = city_dir / f"{city_id}_tiles.geojson" | |
| if tiles_geojson.exists(): | |
| item["assets"]["tile_index"] = { | |
| "href": str(tiles_geojson.relative_to(Path(data_root).parent)), | |
| "type": "application/geo+json", | |
| "title": "Tile index (grid)", | |
| "roles": ["metadata"] | |
| } | |
| meta_json = city_dir / f"{city_id}_metadata.json" | |
| if meta_json.exists(): | |
| item["assets"]["metadata"] = { | |
| "href": str(meta_json.relative_to(Path(data_root).parent)), | |
| "type": "application/json", | |
| "title": "ISO 19115-2 + OGC 23-008r3 metadata", | |
| "roles": ["metadata"] | |
| } | |
| if has_annotations: | |
| item["assets"]["annotations"] = { | |
| "href": str(anno_dir.relative_to(Path(data_root).parent)) + "/", | |
| "type": "application/json", | |
| "title": "Keypoint annotations", | |
| "roles": ["metadata"] | |
| } | |
| item["links"] = [ | |
| {"rel": "self", "href": f"./{city_id}.json", "type": "application/json"}, | |
| {"rel": "collection", "href": "../collection.json", "type": "application/json"}, | |
| {"rel": "root", "href": "../collection.json", "type": "application/json"} | |
| ] | |
| out_path = output_dir / "items" / f"{city_id}.json" | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| out_path.write_text(json.dumps(item, indent=2), encoding="utf-8") | |
| print(f" ✅ Item written: {out_path}") | |
| return item | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Generate STAC metadata for MatchGeo-DEM") | |
| parser.add_argument("--data-root", required=True, help="Path to MatchGeo-DEM-v1/data/") | |
| parser.add_argument("--output", default="stac", help="Output directory for STAC files") | |
| args = parser.parse_args() | |
| data_root = Path(args.data_root) | |
| output_dir = Path(args.output) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| print("=" * 60) | |
| print("MatchGeo-DEM STAC Generator v1.0") | |
| print("=" * 60) | |
| # Build collection | |
| print("\n📦 Building Collection...") | |
| collection = build_collection(data_root, output_dir) | |
| # Build items | |
| print("\n🗺️ Building Items...") | |
| for city in CITIES: | |
| build_item(city, data_root, output_dir) | |
| # Update collection links with item references | |
| for city in CITIES: | |
| collection["links"].append({ | |
| "rel": "item", | |
| "href": f"./items/{city['id']}.json", | |
| "type": "application/json" | |
| }) | |
| # Rewrite collection with item links | |
| (output_dir / "collection.json").write_text( | |
| json.dumps(collection, indent=2), encoding="utf-8" | |
| ) | |
| print("\n" + "=" * 60) | |
| print("✅ STAC metadata complete!") | |
| print(f" Collection: {output_dir / 'collection.json'}") | |
| print(f" Items: {output_dir / 'items/'}") | |
| print("=" * 60) | |
| if __name__ == "__main__": | |
| main() | |