#!/usr/bin/env python3 """Relief LiDAR → dalles pour l'app AR Boucle du Hainaut. Sources : - Wallonie : SPW, Relief de la Wallonie 2021-2022, MNS et MNT 1 m (GeoTIFF EPSG:3812), fichiers province de Hainaut téléchargés en entier (raw/lidar/*.zip). Licence CC-BY 4.0. - Flandre (petite partie du couloir près d'Avelgem) : Digitaal Vlaanderen, DHMV II DSM/DTM 1 m (WCS, EPSG:31370). Modellicentie gratis hergebruik v1.0. Étape A (une fois) : lit les deux ZIP en parallèle, bande par bande, et garde pour le couloir : - ndsm_1m.u8 : hauteur au-dessus du sol (MNS − MNT) par pas de 0,2 m (0–50,8 m), 255 = pas de donnée ; - mnt_10m.f4 : altitude du terrain moyennée par carrés de 10 m. Étape B : dalles de 1 km dans la projection de l'app (équirectangulaire, LAT0 = 50,6°) : - www/data/lidar/{1m,2m,4m}/{kx}_{ky}.png : PNG gris 8 bits, valeur × 0,2 m, max des pixels sources couverts (prudent pour masquer), hauteurs < 1 m mises à 0 ; ligne 0 = bord nord ; - www/data/terrain/{kx}_{ky}.png : 100 × 100 px (10 m), altitude en décimètres = R × 256 + G. Usage : python3 -I tools/build_lidar_tiles.py raw/lidar www/data [--follow] (--follow : les ZIP sont encore en cours de téléchargement ; on attend les octets manquants.) """ import sys, os, io, json, math, struct, time, zlib, datetime, urllib.request import numpy as np import imagecodecs, pyproj, tifffile from PIL import Image R = 6371008.8 K = math.cos(math.radians(50.6)) TILE = 1000 BUF = 3700 # m autour du tracé (couloir de 3 km + marge d'une demi-dalle) STEP = 0.2 # m par niveau de gris MIN_H = 1.0 # m : en dessous, considéré comme sol NODATA = 255 X0, Y0 = 542248.5, 667581.5 # coin haut-gauche de la grille SPW 1 m (EPSG:3812) WAL = pyproj.Transformer.from_crs(4326, 3812, always_xy=True) FLA = pyproj.Transformer.from_crs(4326, 31370, always_xy=True) def app_proj(lon, lat): return R * K * math.radians(lon), R * math.radians(lat) def app_unproj(X, Y): return np.degrees(X / (R * K)), np.degrees(Y / R) # --------------------------------------------------------------------------- couloir def corridor_tiles(trace): pts = np.array([app_proj(lo, la) for la, lo in trace]) dense = [] for a, b in zip(pts, pts[1:]): n = max(1, int(np.hypot(*(b - a)) / 50)) for k in range(n): dense.append(a + (b - a) * k / n) dense = np.array(dense + [pts[-1]]) kx0, ky0 = np.floor((dense.min(0) - BUF) / TILE).astype(int) kx1, ky1 = np.floor((dense.max(0) + BUF) / TILE).astype(int) keys = [] for kx in range(kx0, kx1 + 1): for ky in range(ky0, ky1 + 1): c = np.array([(kx + 0.5) * TILE, (ky + 0.5) * TILE]) if np.min(np.hypot(*(dense - c).T)) < 3000 + TILE * 0.71: keys.append((kx, ky)) return keys def window_3812(keys): xs, ys = [], [] for kx, ky in keys: for X in (kx * TILE, (kx + 1) * TILE): for Y in (ky * TILE, (ky + 1) * TILE): lon, lat = app_unproj(X, Y) x, y = WAL.transform(lon, lat) xs.append(x); ys.append(y) m = 20 c0 = int((min(xs) - m - X0)); c1 = int(math.ceil(max(xs) + m - X0)) r0 = int((Y0 - max(ys) - m)); r1 = int(math.ceil(Y0 - min(ys) + m)) return r0, r1, c0, c1 # --------------------------------------------------------------------------- lecture des ZIP SPW class GrowingFile: """Fichier en cours de téléchargement : attend les octets manquants (mode --follow).""" def __init__(self, path, follow, done_flag): self.f = open(path, 'rb'); self.follow = follow; self.done_flag = done_flag def read(self, n): while True: d = self.f.read(n) if d or not self.follow or self.done_flag(): return d time.sleep(2) def strips(path, follow=False, done_flag=lambda: True): """Générateur : (index de bande, lignes float32 de la bande) d'un ZIP SPW (un BigTIFF LZW en bandes).""" src = GrowingFile(path, follow, done_flag) buf = b'' def need(n): nonlocal buf while len(buf) < n: c = src.read(1 << 20) if not c: raise EOFError(path) buf += c while True: need(30); assert buf[:4] == b'PK\x03\x04' cs = struct.unpack(' 0: del U[:cut]; base += cut s += 1 def step_a(raw, work, win, follow): r0, r1, c0, c1 = win nd_path = os.path.join(work, 'ndsm_1m.u8'); mt_path = os.path.join(work, 'mnt_10m.f4') meta_path = os.path.join(work, 'window.json') if os.path.exists(meta_path) and json.load(open(meta_path)).get('win') == list(win): print('étape A déjà faite', flush=True); return rows, cols = r1 - r0, c1 - c0 nd = np.memmap(nd_path, dtype=np.uint8, mode='w+', shape=(rows, cols)) mt_sum = np.zeros(((rows + 9) // 10, (cols + 9) // 10), np.float64) mt_n = np.zeros_like(mt_sum) done = lambda name: (lambda: 'done' in open(os.path.join(raw, name)).read()) gs = strips(os.path.join(raw, 'MNS_1M_HAINAUT.zip'), follow, done('dl_mns.log')) gt = strips(os.path.join(raw, 'MNT_1M_HAINAUT.zip'), follow, done('dl_mnt.log')) W, H, rps = next(gs); assert next(gt) == (W, H, rps) t0 = time.time() for (s, a), (s2, b) in zip(gs, gt): assert s == s2 y_a = s * rps if y_a + len(a) <= r0: continue if y_a >= r1: break lo = max(r0, y_a); hi = min(r1, y_a + len(a)) A = a[lo - y_a:hi - y_a, c0:c1]; B = b[lo - y_a:hi - y_a, c0:c1] ok = (A > -1000) & (B > -1000) h = np.where(ok, np.clip(np.round((A - B) / STEP), 0, 254), NODATA).astype(np.uint8) nd[lo - r0:hi - r0] = h # MNT 10 m : moyenne des pixels valides par carré de 10 × 10 rr = (np.arange(lo, hi) - r0) // 10 starts = np.arange(0, cols, 10) Bv = np.where(B > -1000, B, 0.0).astype(np.float64); Bn = (B > -1000).astype(np.float64) for k, r in enumerate(rr): mt_sum[r] += np.add.reduceat(Bv[k], starts); mt_n[r] += np.add.reduceat(Bn[k], starts) if s % 200 == 0: print(f' bande {s} (ligne {hi - r0}/{rows}) {time.time() - t0:.0f} s', flush=True) nd.flush() mt = np.where(mt_n > 0, mt_sum / np.maximum(mt_n, 1), np.nan).astype(np.float32) mt.tofile(mt_path) json.dump({'win': list(win), 'mnt_shape': list(mt.shape)}, open(meta_path, 'w')) print(f'étape A finie en {time.time() - t0:.0f} s', flush=True) # --------------------------------------------------------------------------- Flandre (WCS) def fla_window(coverage, x0, y0, x1, y1): url = ('https://geo.api.vlaanderen.be/DHMV/wcs?service=WCS&version=2.0.1&request=GetCoverage' f'&coverageId={coverage}&format=image/tiff&subset=x({x0},{x1})&subset=y({y0},{y1})') for attempt in range(2): try: data = urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'bdh-ar-lidar/1.0'}), timeout=120).read() i = data.find(b'II*\x00') return tifffile.imread(io.BytesIO(data[i:])).astype(np.float32) except Exception as e: print(' WCS Flandre', coverage, e, flush=True); time.sleep(5) raise RuntimeError('WCS Flandre') class Flanders: """nDSM et MNT 1 m flamands autour d'une dalle (chargés à la demande).""" def get(self, lon, lat): x, y = FLA.transform(lon, lat) x0, x1 = int(np.floor(x.min())) - 4, int(np.ceil(x.max())) + 4 y0, y1 = int(np.floor(y.min())) - 4, int(np.ceil(y.max())) + 4 try: dsm = fla_window('DHMVII_DSM_1m', x0, y0, x1, y1) dtm = fla_window('DHMVII_DTM_1m', x0, y0, x1, y1) except RuntimeError: return None # hors de la Flandre (autre province, France…) : pas de donnée, considéré comme sol ok = (dsm > -1000) & (dtm > -1000) nd = np.where(ok, np.clip(np.round((dsm - dtm) / STEP), 0, 254), NODATA).astype(np.uint8) cols = np.clip((x - x0).astype(int), 0, nd.shape[1] - 1) rows = np.clip((y1 - y).astype(int), 0, nd.shape[0] - 1) return nd, dtm, rows, cols # --------------------------------------------------------------------------- étape B def maxpool(a, k): """Maximum glissant k × k (ancré en haut à gauche), en ignorant NODATA.""" if k == 1: return a v = np.where(a == NODATA, 0, a) out = v.copy() for dy in range(k): for dx in range(k): if dx or dy: out[:v.shape[0] - dy, :v.shape[1] - dx] = np.maximum(out[:v.shape[0] - dy, :v.shape[1] - dx], v[dy:, dx:]) out[a == NODATA] = NODATA return out def save_png(path, img, mode): buf = io.BytesIO() Image.fromarray(img, mode).save(buf, 'PNG', optimize=True) data = buf.getvalue() open(path, 'wb').write(data) return len(data) def step_b(work, out, keys, win): r0, r1, c0, c1 = win nd = np.memmap(os.path.join(work, 'ndsm_1m.u8'), dtype=np.uint8, mode='r', shape=(r1 - r0, c1 - c0)) meta = json.load(open(os.path.join(work, 'window.json'))) mt = np.fromfile(os.path.join(work, 'mnt_10m.f4'), dtype=np.float32).reshape(meta['mnt_shape']) fla = Flanders() build = datetime.datetime.now().strftime('%Y%m%d%H%M') stats = {} for res in (1, 2, 4): d = os.path.join(out, 'lidar', f'{res}m'); os.makedirs(d, exist_ok=True) for f in os.listdir(d): os.remove(os.path.join(d, f)) stats[res] = {'tiles': [], 'bytes': 0} dt = os.path.join(out, 'terrain'); os.makedirs(dt, exist_ok=True) for f in os.listdir(dt): os.remove(os.path.join(dt, f)) tstats = {'tiles': [], 'bytes': 0} t0 = time.time() for n, (kx, ky) in enumerate(keys): key = f'{kx}_{ky}' # Grille 1 m (centres de pixels), ligne 0 = nord i = np.arange(1000) + 0.5 X = kx * TILE + i[None, :]; Y = (ky + 1) * TILE - i[:, None] lon, lat = app_unproj(np.broadcast_to(X, (1000, 1000)), np.broadcast_to(Y, (1000, 1000))) x, y = WAL.transform(lon, lat) rows = np.floor(Y0 - y).astype(int) - r0; cols = np.floor(x - X0).astype(int) - c0 rr0, rr1 = rows.min() - 4, rows.max() + 5; cc0, cc1 = cols.min() - 4, cols.max() + 5 win_a = np.array(nd[max(rr0, 0):rr1, max(cc0, 0):cc1]) if rr0 < 0 or cc0 < 0: pad = np.full((rr1 - rr0, cc1 - cc0), NODATA, np.uint8) pad[max(rr0, 0) - rr0:max(rr0, 0) - rr0 + win_a.shape[0], max(cc0, 0) - cc0:max(cc0, 0) - cc0 + win_a.shape[1]] = win_a win_a = pad lr, lc = rows - rr0, cols - cc0 need_fla = bool((win_a[lr, lc] == NODATA).any()) fl = fla.get(lon, lat) if need_fla else None if need_fla: print(f' {key} : complété par la Flandre' if fl is not None else f' {key} : zone sans données (hors Wallonie et Flandre)', flush=True) for res in (1, 2, 4): pooled = maxpool(win_a, res) # pixel de sortie res m : max des res × res pixels 1 m couverts (coin nord-ouest) s = slice(0, 1000, res) img = pooled[lr[s, s], lc[s, s]] if fl is not None: fnd, _, frows, fcols = fl fp = maxpool(fnd, res)[frows[s, s], fcols[s, s]] img = np.where(img == NODATA, fp, img) img = np.where(img == NODATA, 0, img).astype(np.uint8) img[img < MIN_H / STEP] = 0 if img.any(): stats[res]['bytes'] += save_png(os.path.join(out, 'lidar', f'{res}m', key + '.png'), img, 'L') stats[res]['tiles'].append(key) # Terrain 10 m s10 = slice(5, 1000, 10) tr = np.clip(((Y0 - y[s10, s10]) - r0) // 10, 0, mt.shape[0] - 1).astype(int) tc = np.clip(((x[s10, s10] - X0) - c0) // 10, 0, mt.shape[1] - 1).astype(int) alt = mt[tr, tc] if fl is not None: _, fdtm, frows, fcols = fl fa = fdtm[frows[s10, s10], fcols[s10, s10]] alt = np.where(np.isnan(alt) & (fa > -1000), fa, alt) if not np.isnan(alt).all(): alt = np.where(np.isnan(alt), np.nanmean(alt), alt) dm = np.clip(np.round(alt * 10), 0, 65535).astype(np.uint16) rgb = np.zeros((100, 100, 3), np.uint8); rgb[..., 0] = dm >> 8; rgb[..., 1] = dm & 255 tstats['bytes'] += save_png(os.path.join(dt, key + '.png'), rgb, 'RGB') tstats['tiles'].append(key) if n % 25 == 0: print(f' dalle {n + 1}/{len(keys)} {key}{" (Flandre)" if need_fla else ""} {time.time() - t0:.0f} s', flush=True) src_w = ('Service public de Wallonie (SPW) - Relief de la Wallonie - MNS et MNT 1 m 2021-2022, CC-BY 4.0 ' '(https://geodata.wallonie.be/id/e82665e2-4f89-4b7b-87a0-e77a4d4d9c5b, ' 'https://geodata.wallonie.be/id/fe13bc84-e371-46ca-9632-8ad4139f1ee5)') src_f = 'Bron: Digitaal Vlaanderen - DHMV II DSM/DTM 1 m (Modellicentie gratis hergebruik v1.0)' for res in (1, 2, 4): json.dump({'tiles': stats[res]['tiles'], 'tileSize': TILE, 'res': res, 'px': TILE // res, 'step': STEP, 'minHeight': MIN_H, 'bytes': stats[res]['bytes'], 'build': build, 'source': [src_w, src_f], 'units': 'gris × 0,2 m = hauteur au-dessus du sol (max des pixels 1 m couverts), ligne 0 = nord'}, open(os.path.join(out, 'lidar', f'{res}m', 'index.json'), 'w')) print(f'{res} m : {len(stats[res]["tiles"])} dalles, {stats[res]["bytes"] / 1e6:.1f} Mo', flush=True) json.dump({'tiles': tstats['tiles'], 'tileSize': TILE, 'res': 10, 'px': 100, 'bytes': tstats['bytes'], 'build': build, 'source': [src_w, src_f], 'units': 'altitude (m, DNG) × 10 = R × 256 + G, ligne 0 = nord'}, open(os.path.join(dt, 'index.json'), 'w')) print(f'terrain 10 m : {len(tstats["tiles"])} dalles, {tstats["bytes"] / 1e6:.1f} Mo', flush=True) def main(raw, out, follow=False): trace = json.load(open(os.path.join(out, 'trace.json')))['line'] keys = corridor_tiles(trace) win = window_3812(keys) print(f'{len(keys)} dalles, fenêtre SPW lignes {win[0]}–{win[1]}, colonnes {win[2]}–{win[3]}', flush=True) work = os.path.join(raw, 'work'); os.makedirs(work, exist_ok=True) step_a(raw, work, win, follow) step_b(work, out, keys, win) if __name__ == '__main__': args = [a for a in sys.argv[1:] if not a.startswith('--')] main(*args, follow='--follow' in sys.argv)