#!/usr/bin/env python3 """Segment a hand-drawn town map bitmap into roof, tree and water masks. Tuned for the common "parchment with dark roofs, cauliflower tree glyphs, teal water" style of map exporters. Every threshold is a flag so you can tune it to your own map; `--look` writes a check image you MUST eyeball before building the massing (false "trees" that are really roof detail are the usual miss). usage: segment_map.py MAP.png --mpp 0.5 --out seg.npz [--look look.jpg] [--roof-max 184] [--tree-glyph-px 5] """ import argparse import cv2 import numpy as np from PIL import Image from citykit import ell Image.MAX_IMAGE_PIXELS = None def lstd(g, k): return np.sqrt(np.maximum(cv2.blur(g * g, (k, k)) - cv2.blur(g, (k, k)) ** 2, 0)) def segment(rgb, mpp, roof_max=184.0, tree_glyph_px=5, tree_min_m2=8.0, tree_max_m2=700.0, roof_min_m2=11.0, water_gr=22, water_br=12): """Return (roof, tree, water) uint8 masks. `mpp` scales the morphology windows so the same flags work across export resolutions (the reference tuning was at 0.53 m/px).""" s = 0.53 / mpp # window scale relative to the reference tuning a = rgb.astype(np.float32) R, G, B = a[..., 0], a[..., 1], a[..., 2] g = 0.3 * R + 0.59 * G + 0.11 * B gb = cv2.blur(g, (3, 3)) # trees: dense short dark strokes (blackhat line density) in compact blobs bh = cv2.morphologyEx(g, cv2.MORPH_BLACKHAT, ell(tree_glyph_px * s)) ld = cv2.blur((bh > 12).astype(np.float32), (int(9 * s) | 1,) * 2) tr = ((ld > 0.45) & (cv2.blur(g, (int(9 * s) | 1,) * 2) < 175)).astype(np.uint8) tr = cv2.morphologyEx(tr, cv2.MORPH_OPEN, ell(5 * s)) tr = cv2.morphologyEx(tr, cv2.MORPH_CLOSE, ell(3 * s)) n, lab, st, _ = cv2.connectedComponentsWithStats(tr, 8) keep = np.zeros(n, bool) for i in range(1, n): x, y, w, h, ar = st[i] area_m2 = ar * mpp * mpp if area_m2 < tree_min_m2 or area_m2 > tree_max_m2: continue if max(w, h) > 2.6 * min(w, h): continue if ar / float(w * h) < 0.4: continue keep[i] = True tree = cv2.dilate(keep[lab].astype(np.uint8), ell(3 * s)) # roofs: darker than the parchment and not a tree; fill small holes; strip the 1 px cast-shadow halo roof = ((gb < roof_max) & (cv2.dilate(tree, ell(3 * s)) == 0)).astype(np.uint8) roof = cv2.morphologyEx(roof, cv2.MORPH_OPEN, ell(3 * s)) roof = cv2.morphologyEx(roof, cv2.MORPH_CLOSE, ell(3 * s)) inv = (1 - roof).astype(np.uint8) n, lab, st, _ = cv2.connectedComponentsWithStats(inv, 4) hole = np.zeros(n, bool) hole[1:] = st[1:, 4] * mpp * mpp < 25.0 roof[hole[lab] & (tree == 0)] = 1 roof = cv2.erode(roof, ell(3 * s)) n, lab, st, _ = cv2.connectedComponentsWithStats(roof, 8) keep = np.zeros(n, bool) keep[1:] = st[1:, 4] * mpp * mpp >= roof_min_m2 roof = keep[lab].astype(np.uint8) water = ((G - R > water_gr) & (B - R > water_br)).astype(np.uint8) water = cv2.morphologyEx(water, cv2.MORPH_OPEN, ell(3 * s)) water = cv2.morphologyEx(water, cv2.MORPH_CLOSE, ell(5 * s)) roof[water > 0] = 0 tree[water > 0] = 0 return roof, tree, water def look_image(rgb, roof, tree, water): a = rgb.copy() a[roof > 0] = (a[roof > 0] * 0.45 + np.array([255, 0, 0]) * 0.55).astype(np.uint8) a[tree > 0] = (a[tree > 0] * 0.45 + np.array([0, 200, 0]) * 0.55).astype(np.uint8) a[water > 0] = (a[water > 0] * 0.45 + np.array([0, 80, 255]) * 0.55).astype(np.uint8) return np.concatenate([rgb, a], 1) if __name__ == "__main__": ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("map") ap.add_argument("--mpp", type=float, required=True, help="meters per bitmap pixel") ap.add_argument("--out", default="seg.npz") ap.add_argument("--look", default=None, help="write a before/after check image (downscaled to 2400 px wide)") ap.add_argument("--roof-max", type=float, default=184.0, help="gray level below which a pixel can be roof") ap.add_argument("--tree-glyph-px", type=int, default=5) a = ap.parse_args() im = np.asarray(Image.open(a.map).convert("RGB")) roof, tree, water = segment(im, a.mpp, a.roof_max, a.tree_glyph_px) np.savez_compressed(a.out, roof=roof, tree=tree, water=water, mpp=np.float32(a.mpp)) print("roof %.4f tree %.4f water %.4f of the bitmap" % (roof.mean(), tree.mean(), water.mean())) if a.look: lk = look_image(im, roof, tree, water) sc = min(1.0, 2400 / lk.shape[1]) if sc < 1: lk = cv2.resize(lk, None, fx=sc, fy=sc, interpolation=cv2.INTER_AREA) Image.fromarray(lk).save(a.look, quality=88) print("check image:", a.look)