City3D-MultiGen / scripts /holicity /Obtain_corresponding_map_signed.py
e32's picture
Initial release: reconstruction pipeline + metadata
e95f494 verified
Raw
History Blame Contribute Delete
12.3 kB
"""
Fetch satellite and styled basemap imagery and derive per-class semantic masks
(HoliCity / London variant of the City3D-MultiGen reconstruction pipeline).
Pipeline role:
For each 150 m tile this script downloads a satellite image and a custom-styled
Google "roadmap" basemap from the Google Maps Static API (using URL signing),
crops both to the tile's WGS84 bounding box, and parses the styled basemap into
binary semantic masks by exact/tolerant color matching against CLASS_COLORS_HEX.
Inputs:
- A folder (default ``./output``) of per-tile JSON files, each providing the tile
corners ``wgs84_nw`` = [west_lon, north_lat] and ``wgs84_se`` = [east_lon, south_lat].
Outputs (written next to each ``<base>.json``, sharing its base name):
- ``<base>_sat.png`` : cropped satellite image of the tile.
- ``<base>_map.png`` : cropped custom-styled basemap of the tile.
- Six binary masks ``<base>_<Class>.png`` for Building, RoadSurface, Railway,
VegetationLand, UrbanLand and WaterSurface (255 = class pixel, 0 = background).
Key steps:
1. Compute the tile center and download satellite + styled basemap tiles (zoom 18).
2. Web-Mercator project the bounding box and crop both images to the tile extent.
3. Match styled-map colors per class (exact match, tolerant + 1px dilation for Railway)
and save one mask per class. Already-processed tiles are skipped.
Required environment variables (no defaults; the script reads them as-is):
- GOOGLE_MAPS_API_KEY : Google Maps Static API key.
- GOOGLE_MAPS_URL_SIGNING_SECRET : URL signing secret used to sign each request.
- GOOGLE_MAPS_STYLE_MAP_ID : Cloud-based map style ID defining the semantic-class
colors. You must recreate the custom styled map in your own Google Cloud account.
"""
import os
import json
import math
import io
import time
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
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}")
if __name__ == "__main__":
folder = "./output"
api_key = os.environ.get("GOOGLE_MAPS_API_KEY")
url_signing_secret = os.environ.get("GOOGLE_MAPS_URL_SIGNING_SECRET")
# Your own Google Cloud map-style ID (defines the semantic-class colors).
# See README: you must recreate the styled map in your own account.
style_map_id = os.environ.get("GOOGLE_MAPS_STYLE_MAP_ID")
process_folder(folder, api_key, url_signing_secret, style_map_id)