Datasets:
Tasks:
Image-to-3D
Modalities:
Geospatial
Languages:
English
Size:
100K<n<1M
Tags:
3d-point-cloud
point-cloud-generation
city-scale
remote-sensing
satellite-imagery
digital-surface-model
License:
| """Fetch per-tile imagery and derive semantic masks for the City3D-MultiGen | |
| reconstruction pipeline (GridFlow, ECCV 2026). | |
| Pipeline role: | |
| For each 150 m tile this script downloads two co-registered rasters from the | |
| signed Google Maps Static API -- a satellite image and a custom-styled | |
| "roadmap" image -- then parses the styled roadmap into per-class binary | |
| semantic masks using fixed color thresholds. | |
| Inputs: | |
| Tile geo-extents read from per-tile JSON metadata files (``wgs84_nw`` / | |
| ``wgs84_se`` lon/lat corners). These JSONs can optionally be generated first | |
| from an area bounding box (``--nw`` / ``--se``). | |
| Outputs (written next to each JSON, keyed by the tile base name): | |
| ``<base>_sat.png`` satellite crop, ``<base>_map.png`` styled roadmap crop, | |
| and six mask images ``<base>_<Class>.png`` for the classes Building, | |
| RoadSurface, Railway, VegetationLand, UrbanLand and WaterSurface. | |
| Key steps: | |
| 1. Build the Static Maps URL, sign it with the URL-signing secret (HMAC-SHA1). | |
| 2. Fetch satellite and styled-roadmap tiles, then crop to the exact extent. | |
| 3. Parse the roadmap crop into masks via the CLASS_COLORS_HEX color thresholds | |
| (exact match per class; tolerant match plus 1 px dilation for Railway). | |
| Required environment variables (each may be overridden by a CLI flag): | |
| GOOGLE_MAPS_API_KEY Static Maps API key. | |
| GOOGLE_MAPS_URL_SIGNING_SECRET URL-signing secret for the signed requests. | |
| GOOGLE_MAPS_STYLE_MAP_ID Map ID of the custom roadmap style. | |
| Note: the custom Google map style referenced by GOOGLE_MAPS_STYLE_MAP_ID is not | |
| distributed here; you must recreate it in the Google Cloud console so the styled | |
| roadmap colors match the CLASS_COLORS_HEX values used for mask parsing. | |
| """ | |
| import os | |
| import json | |
| import math | |
| import io | |
| import time | |
| import argparse | |
| import requests | |
| from requests.adapters import HTTPAdapter | |
| from urllib3.util.retry import Retry | |
| from PIL import Image | |
| import numpy as np | |
| from tqdm import tqdm | |
| import hashlib | |
| import hmac | |
| import base64 | |
| import urllib.parse as urlparse | |
| from pyproj import Transformer | |
| CLASS_COLORS_HEX = { | |
| "RoadSurface": ["1e1e1e"], | |
| "Building": ["ff0000"], | |
| "Railway": ["0073ff"], | |
| "VegetationLand": ["c3f1d5"], | |
| "UrbanLand": ["f5f0e5", "d3f8e2"], | |
| "WaterSurface": ["90daee"], | |
| } | |
| def hex_to_rgb(hex_str): | |
| h = hex_str.strip().lower() | |
| return ( | |
| int(h[0:2], 16), | |
| int(h[2:4], 16), | |
| int(h[4:6], 16), | |
| ) | |
| CLASS_COLORS_RGB = { | |
| class_name: [hex_to_rgb(code) for code in hex_list] | |
| for class_name, hex_list in CLASS_COLORS_HEX.items() | |
| } | |
| def sign_url(input_url, secret): | |
| if not input_url or not secret: | |
| raise Exception("Both input_url and secret are required") | |
| url = urlparse.urlparse(input_url) | |
| url_to_sign = url.path + "?" + url.query | |
| decoded_key = base64.urlsafe_b64decode(secret) | |
| signature = hmac.new(decoded_key, str.encode(url_to_sign), hashlib.sha1) | |
| encoded_signature = base64.urlsafe_b64encode(signature.digest()) | |
| original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query | |
| return original_url + "&signature=" + encoded_signature.decode() | |
| def dilate_mask_1px(mask_arr): | |
| h, w = mask_arr.shape | |
| out = np.zeros((h, w), dtype=np.uint8) | |
| ys, xs = np.nonzero(mask_arr > 0) | |
| for y, x in zip(ys, xs): | |
| y0 = max(y - 1, 0) | |
| y1 = min(y + 1, h - 1) | |
| x0 = max(x - 1, 0) | |
| x1 = min(x + 1, w - 1) | |
| out[y0:y1+1, x0:x1+1] = 255 | |
| return out | |
| def match_mask_exact(arr, rgb_triplet): | |
| r, g, b = rgb_triplet | |
| return ( | |
| (arr[:, :, 0] == r) & | |
| (arr[:, :, 1] == g) & | |
| (arr[:, :, 2] == b) | |
| ) | |
| def channel_bounds_with_margin(channel_val, margin_ratio): | |
| low = int(round(channel_val * (1.0 - margin_ratio))) | |
| high = int(round(channel_val * (1.0 + margin_ratio))) | |
| if low < 0: | |
| low = 0 | |
| if high > 255: | |
| high = 255 | |
| return low, high | |
| def match_mask_tolerant(arr, rgb_triplet, margin_ratio): | |
| r, g, b = rgb_triplet | |
| rl, rh = channel_bounds_with_margin(r, margin_ratio) | |
| gl, gh = channel_bounds_with_margin(g, margin_ratio) | |
| bl, bh = channel_bounds_with_margin(b, margin_ratio) | |
| return ( | |
| (arr[:, :, 0] >= rl) & (arr[:, :, 0] <= rh) & | |
| (arr[:, :, 1] >= gl) & (arr[:, :, 1] <= gh) & | |
| (arr[:, :, 2] >= bl) & (arr[:, :, 2] <= bh) | |
| ) | |
| def generate_masks_from_roadmap(crop_road_img, base_output_path_no_ext): | |
| rgb = crop_road_img.convert("RGB") | |
| arr = np.array(rgb, dtype=np.uint8) | |
| for class_name, rgb_list in CLASS_COLORS_RGB.items(): | |
| class_mask_total = np.zeros(arr.shape[:2], dtype=np.uint8) | |
| for rgb_triplet in rgb_list: | |
| if class_name == "Railway": | |
| match = match_mask_tolerant(arr, rgb_triplet, margin_ratio=0.1) | |
| else: | |
| match = match_mask_exact(arr, rgb_triplet) | |
| class_mask_total[match] = 255 | |
| if class_name == "Railway": | |
| class_mask_total = dilate_mask_1px(class_mask_total) | |
| out_path = f"{base_output_path_no_ext}_{class_name}.png" | |
| img = Image.fromarray(class_mask_total) | |
| img.save(out_path) | |
| def save_bbox_satellite_and_roadmap( | |
| north_lat, | |
| west_lon, | |
| south_lat, | |
| east_lon, | |
| out_path_sat, | |
| out_path_road, | |
| api_key, | |
| url_signing_secret, | |
| style_map_id | |
| ): | |
| def mercator_project(lon_deg, lat_deg, zoom): | |
| scale = 256 * (2 ** zoom) | |
| x = (lon_deg + 180.0) / 360.0 * scale | |
| lat_rad = math.radians(lat_deg) | |
| y = (1.0 - math.log(math.tan(lat_rad) + 1.0 / math.cos(lat_rad)) / math.pi) / 2.0 * scale | |
| return x, y | |
| def bbox_center(n_lat, s_lat, w_lon, e_lon): | |
| return ( | |
| (n_lat + s_lat) / 2.0, | |
| (w_lon + e_lon) / 2.0 | |
| ) | |
| def download_static(center_lat, center_lon, zoom, size_px, maptype, api_key, url_signing_secret, style_map_id=None): | |
| session = requests.Session() | |
| retry_strategy = Retry( | |
| total=5, | |
| backoff_factor=2, | |
| status_forcelist=[429, 500, 502, 503, 504], | |
| allowed_methods=["GET"] | |
| ) | |
| adapter = HTTPAdapter(max_retries=retry_strategy) | |
| session.mount("https://", adapter) | |
| session.mount("http://", adapter) | |
| base = "https://maps.googleapis.com/maps/api/staticmap" | |
| params = { | |
| "center": f"{center_lat},{center_lon}", | |
| "zoom": str(18), | |
| "size": f"{size_px}x{size_px}", | |
| "format": "png", | |
| "key": api_key, | |
| } | |
| if maptype == "satellite": | |
| params["maptype"] = "satellite" | |
| else: | |
| params["map_id"] = style_map_id | |
| query_string = "&".join([f"{k}={urlparse.quote(str(v), safe='')}" for k, v in params.items()]) | |
| unsigned_url = f"{base}?{query_string}" | |
| signed_url = sign_url(unsigned_url, url_signing_secret) | |
| max_retries = 3 | |
| for attempt in range(max_retries): | |
| try: | |
| resp = session.get(signed_url, timeout=30) | |
| resp.raise_for_status() | |
| time.sleep(0.5) | |
| return Image.open(io.BytesIO(resp.content)).convert("RGBA") | |
| except (requests.exceptions.ConnectionError, | |
| requests.exceptions.Timeout, | |
| requests.exceptions.RequestException) as e: | |
| if attempt < max_retries - 1: | |
| wait_time = (attempt + 1) * 5 | |
| print(f"\nRequest failed, retrying in {wait_time} seconds...") | |
| time.sleep(wait_time) | |
| else: | |
| raise | |
| def crop_bbox_from_image(img, zoom, img_px, center_lat, center_lon, | |
| n_lat, s_lat, w_lon, e_lon): | |
| center_x, center_y = mercator_project(center_lon, center_lat, zoom) | |
| img_left_world = center_x - img_px / 2.0 | |
| img_top_world = center_y - img_px / 2.0 | |
| w_x, _ = mercator_project(w_lon, center_lat, zoom) | |
| e_x, _ = mercator_project(e_lon, center_lat, zoom) | |
| _, n_y = mercator_project(center_lon, n_lat, zoom) | |
| _, s_y = mercator_project(center_lon, s_lat, zoom) | |
| xmin = w_x - img_left_world | |
| xmax = e_x - img_left_world | |
| ymin = n_y - img_top_world | |
| ymax = s_y - img_top_world | |
| box = ( | |
| int(round(xmin)), | |
| int(round(ymin)), | |
| int(round(xmax)), | |
| int(round(ymax)), | |
| ) | |
| box = ( | |
| max(0, box[0]), | |
| max(0, box[1]), | |
| min(img_px, box[2]), | |
| min(img_px, box[3]), | |
| ) | |
| return img.crop(box) | |
| zoom = 18 | |
| img_px = 600 | |
| center_lat, center_lon = bbox_center(north_lat, south_lat, west_lon, east_lon) | |
| img_sat = download_static(center_lat, center_lon, zoom, img_px, "satellite", api_key, url_signing_secret, style_map_id=None) | |
| img_road = download_static(center_lat, center_lon, zoom, img_px, "roadmap", api_key, url_signing_secret, style_map_id=style_map_id) | |
| crop_sat = crop_bbox_from_image( | |
| img_sat, zoom, img_px, center_lat, center_lon, | |
| north_lat, south_lat, west_lon, east_lon | |
| ) | |
| crop_road = crop_bbox_from_image( | |
| img_road, zoom, img_px, center_lat, center_lon, | |
| north_lat, south_lat, west_lon, east_lon | |
| ) | |
| crop_sat.save(out_path_sat) | |
| crop_road.save(out_path_road) | |
| return crop_sat, crop_road | |
| def process_folder( | |
| folder_path, | |
| api_key, | |
| url_signing_secret, | |
| style_map_id | |
| ): | |
| json_files = [f for f in os.listdir(folder_path) if f.lower().endswith(".json")] | |
| skipped = 0 | |
| failed = 0 | |
| failed_files = [] | |
| for filename in tqdm(json_files, desc="Processing files", unit="file"): | |
| try: | |
| json_path = os.path.join(folder_path, filename) | |
| base_name = os.path.splitext(filename)[0] | |
| out_sat = os.path.join(folder_path, base_name + "_sat.png") | |
| out_map = os.path.join(folder_path, base_name + "_map.png") | |
| expected_files = [out_sat, out_map] | |
| for class_name in CLASS_COLORS_RGB.keys(): | |
| expected_files.append(os.path.join(folder_path, f"{base_name}_{class_name}.png")) | |
| if all(os.path.exists(f) for f in expected_files): | |
| skipped += 1 | |
| continue | |
| with open(json_path, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| wgs84_nw = data["wgs84_nw"] | |
| wgs84_se = data["wgs84_se"] | |
| west_lon = float(wgs84_nw[0]) | |
| north_lat = float(wgs84_nw[1]) | |
| east_lon = float(wgs84_se[0]) | |
| south_lat = float(wgs84_se[1]) | |
| crop_sat, crop_road = save_bbox_satellite_and_roadmap( | |
| north_lat = north_lat, | |
| west_lon = west_lon, | |
| south_lat = south_lat, | |
| east_lon = east_lon, | |
| out_path_sat = out_sat, | |
| out_path_road = out_map, | |
| api_key = api_key, | |
| url_signing_secret = url_signing_secret, | |
| style_map_id = style_map_id | |
| ) | |
| base_mask_prefix = os.path.join(folder_path, base_name) | |
| generate_masks_from_roadmap(crop_road, base_mask_prefix) | |
| except Exception as e: | |
| failed += 1 | |
| failed_files.append(filename) | |
| print(f"\nFailed to process {filename}: {str(e)}") | |
| continue | |
| print(f"\nProcessing complete!") | |
| if skipped > 0: | |
| print(f"Skipped {skipped} already processed files") | |
| if failed > 0: | |
| print(f"Failed to process {failed} files:") | |
| for f in failed_files: | |
| print(f" - {f}") | |
| def make_utm_transformers(center_lat, center_lon): | |
| zone = int((center_lon + 180) / 6) + 1 | |
| epsg = (32600 if center_lat >= 0 else 32700) + zone | |
| to_utm = Transformer.from_crs("EPSG:4326", f"EPSG:{epsg}", always_xy=True) | |
| to_wgs = Transformer.from_crs(f"EPSG:{epsg}", "EPSG:4326", always_xy=True) | |
| return to_utm, to_wgs, epsg | |
| def generate_tile_metadata_for_area( | |
| nw_lat, | |
| nw_lon, | |
| se_lat, | |
| se_lon, | |
| output_folder, | |
| tile_size_m=150.0, | |
| grid_step_m=20.0, | |
| grid_id_start=0, | |
| overwrite=False, | |
| ): | |
| """Tile a lat/lon bounding box into JSON metadata files compatible with | |
| the Melbourne dataset format (utm_nw / utm_se / wgs84_nw / wgs84_se / row / col). | |
| Args: | |
| nw_lat, nw_lon: northwest corner of the area (degrees). | |
| se_lat, se_lon: southeast corner of the area (degrees). | |
| output_folder: where JSON files will be written. | |
| tile_size_m: edge length of each tile in meters (default 150, matches dataset). | |
| grid_step_m: spacing between adjacent tile centers (default 20, matches dataset). | |
| grid_id_start: starting grid_id for filenames (grid_NNNNNN). | |
| overwrite: if False, existing JSONs are kept. | |
| Returns: | |
| list of file paths to the generated JSON files. | |
| """ | |
| os.makedirs(output_folder, exist_ok=True) | |
| center_lat = (nw_lat + se_lat) / 2.0 | |
| center_lon = (nw_lon + se_lon) / 2.0 | |
| to_utm, to_wgs, epsg = make_utm_transformers(center_lat, center_lon) | |
| nw_x, nw_y = to_utm.transform(nw_lon, nw_lat) | |
| se_x, se_y = to_utm.transform(se_lon, se_lat) | |
| x_min, x_max = min(nw_x, se_x), max(nw_x, se_x) | |
| y_min, y_max = min(nw_y, se_y), max(nw_y, se_y) | |
| half = tile_size_m / 2.0 | |
| n_cols = max(1, int(math.ceil((x_max - x_min) / grid_step_m))) | |
| n_rows = max(1, int(math.ceil((y_max - y_min) / grid_step_m))) | |
| print(f"Area UTM (EPSG:{epsg}): x=[{x_min:.1f},{x_max:.1f}] " | |
| f"y=[{y_min:.1f},{y_max:.1f}]") | |
| print(f"Extent: {x_max-x_min:.0f}m x {y_max-y_min:.0f}m " | |
| f"-> grid {n_rows} rows x {n_cols} cols " | |
| f"({n_rows*n_cols} tiles, step={grid_step_m}m, tile={tile_size_m}m)") | |
| written = [] | |
| grid_id = grid_id_start | |
| for row in range(n_rows): | |
| cy = y_max - half - row * grid_step_m | |
| for col in range(n_cols): | |
| cx = x_min + half + col * grid_step_m | |
| utm_nw = [cx - half, cy + half] | |
| utm_se = [cx + half, cy - half] | |
| nw_lon_wgs, nw_lat_wgs = to_wgs.transform(utm_nw[0], utm_nw[1]) | |
| se_lon_wgs, se_lat_wgs = to_wgs.transform(utm_se[0], utm_se[1]) | |
| base_name = f"grid_{grid_id:06d}" | |
| out_path = os.path.join(output_folder, base_name + ".json") | |
| if os.path.exists(out_path) and not overwrite: | |
| grid_id += 1 | |
| written.append(out_path) | |
| continue | |
| meta = { | |
| "grid_id": grid_id, | |
| "row": row, | |
| "col": col, | |
| "utm_nw": utm_nw, | |
| "utm_se": utm_se, | |
| "wgs84_nw": [nw_lon_wgs, nw_lat_wgs], | |
| "wgs84_se": [se_lon_wgs, se_lat_wgs], | |
| "utm_epsg": epsg, | |
| "elevation": { | |
| "local_min_elevation": 0.0, | |
| "local_max_elevation": 0.0, | |
| "global_min_used": -20.0, | |
| "global_max_used": 302.0, | |
| "elevation_range": 0.0, | |
| }, | |
| } | |
| with open(out_path, "w", encoding="utf-8") as f: | |
| json.dump(meta, f, indent=2) | |
| written.append(out_path) | |
| grid_id += 1 | |
| print(f"Wrote {len(written)} tile JSONs to {output_folder}") | |
| return written | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser( | |
| description="Fetch satellite + styled-roadmap tiles and class masks " | |
| "for an area (DSM/point-cloud not generated)." | |
| ) | |
| parser.add_argument("--folder", default="./output", | |
| help="Output folder. If --nw/--se given, JSONs are " | |
| "created here first; otherwise existing JSONs " | |
| "in this folder are processed.") | |
| parser.add_argument("--nw", default=None, | |
| help="Northwest corner 'lat,lon' (e.g. -37.778,144.932).") | |
| parser.add_argument("--se", default=None, | |
| help="Southeast corner 'lat,lon' (e.g. -37.785,144.948).") | |
| parser.add_argument("--tile_size", type=float, default=150.0, | |
| help="Tile edge length in meters (default 150).") | |
| parser.add_argument("--grid_step", type=float, default=20.0, | |
| help="Spacing between tile centers in meters " | |
| "(default 20 = dense dataset grid). Use a value " | |
| "close to --tile_size for non-overlapping coverage " | |
| "with far fewer API calls.") | |
| parser.add_argument("--grid_id_start", type=int, default=0) | |
| parser.add_argument("--api_key", | |
| default=os.environ.get("GOOGLE_MAPS_API_KEY")) | |
| parser.add_argument("--url_signing_secret", | |
| default=os.environ.get("GOOGLE_MAPS_URL_SIGNING_SECRET")) | |
| parser.add_argument("--style_map_id", | |
| default=os.environ.get("GOOGLE_MAPS_STYLE_MAP_ID")) | |
| args = parser.parse_args() | |
| if (args.nw is None) ^ (args.se is None): | |
| parser.error("--nw and --se must be provided together.") | |
| if args.nw and args.se: | |
| nw_lat, nw_lon = [float(v) for v in args.nw.split(",")] | |
| se_lat, se_lon = [float(v) for v in args.se.split(",")] | |
| generate_tile_metadata_for_area( | |
| nw_lat=nw_lat, nw_lon=nw_lon, | |
| se_lat=se_lat, se_lon=se_lon, | |
| output_folder=args.folder, | |
| tile_size_m=args.tile_size, | |
| grid_step_m=args.grid_step, | |
| grid_id_start=args.grid_id_start, | |
| ) | |
| process_folder( | |
| args.folder, | |
| args.api_key, | |
| args.url_signing_secret, | |
| args.style_map_id, | |
| ) | |