""" Server-side segmentation for MAPS-to-DXF. Exposes POST /segment: image file + extent (minX, maxX, minY, maxY). Returns JSON: { buildings: [{ points: [{x,y}] }], trees: [...], lots: [...] } in world meters. Modes: - OpenCV Canny + contours (default): good for aerial/satellite imagery. - Threshold mode (NYPL map-vectorizer style): brightness + contrast + threshold to get a binary image (lines/features dark, rest light), then contours. Good for line-drawing or high-contrast maps. Inspired by https://github.com/nypl-spacetime/map-vectorizer. Optional: pip install vtracer and set USE_VTRACER=1 for visioncortex VTracer. """ import os import re import xml.etree.ElementTree as ET from flask import Flask, request, jsonify app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB try: import cv2 import numpy as np HAS_OPENCV = True except ImportError: HAS_OPENCV = False try: import vtracer HAS_VTRACER = True except ImportError: HAS_VTRACER = False def pixel_contour_to_world(contour, img_w, img_h, min_x, max_x, min_y, max_y): """Convert contour (Nx1x2 OpenCV format) to world coords.""" out = [] for i in range(len(contour)): pt = contour[i] # OpenCV contour shape is (N, 1, 2) px = float(pt[0][0]) py = float(pt[0][1]) x = min_x + (px / img_w) * (max_x - min_x) y = max_y - (py / img_h) * (max_y - min_y) # image y down -> world y up out.append({'x': round(x, 4), 'y': round(y, 4)}) return out def polygon_area_world(points): if len(points) < 3: return 0.0 a = 0.0 for i in range(len(points)): j = (i + 1) % len(points) a += points[i]['x'] * points[j]['y'] - points[j]['x'] * points[i]['y'] return abs(a) / 2.0 def polygon_perimeter_world(points): if len(points) < 2: return 0.0 p = 0.0 for i in range(len(points)): a, b = points[i], points[(i + 1) % len(points)] p += ((b['x'] - a['x']) ** 2 + (b['y'] - a['y']) ** 2) ** 0.5 return p def classify_contour(points): """Classify as 'building' | 'tree' | 'lot' | None. Lots must be parcel-like (compact).""" area = polygon_area_world(points) perim = polygon_perimeter_world(points) if perim < 0.5: return None compactness = (4 * 3.14159265359 * area) / (perim * perim) if 2 <= area <= 55 and compactness > 0.35: return 'tree' if 15 <= area <= 900 and compactness > 0.10: return 'building' # Lots: compactness > 0.08, 150–20k m² — avoids thin strips and irregular blobs if 150 <= area <= 20000 and compactness > 0.08: return 'lot' return None def douglas_peucker(points, eps): if len(points) <= 2: return points a, b = points[0], points[-1] max_d, idx = 0.0, 0 for i in range(1, len(points) - 1): p = points[i] d = abs((b['y'] - a['y']) * p['x'] - (b['x'] - a['x']) * p['y'] + b['x'] * a['y'] - b['y'] * a['x']) denom = ((b['x'] - a['x']) ** 2 + (b['y'] - a['y']) ** 2) ** 0.5 if denom > 1e-10: d /= denom if d > max_d: max_d, idx = d, i if max_d < eps: return [a, b] left = douglas_peucker(points[: idx + 1], eps) right = douglas_peucker(points[idx:], eps) return left[:-1] + right def _contours_to_result(contours, img_bgr, min_x, max_x, min_y, max_y): """Shared: filter contours, simplify, convert to world coords, classify. Returns { buildings, trees, lots }.""" h, w = img_bgr.shape[:2] buildings = [] trees = [] lots = [] for cnt in contours: if cnt.shape[0] < 4: continue epsilon = 0.01 * cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, epsilon, True) if approx.shape[0] < 3: continue pts = pixel_contour_to_world(approx, w, h, min_x, max_x, min_y, max_y) if polygon_area_world(pts) < 15: continue kind = classify_contour(pts) if kind == 'building': buildings.append(pts) elif kind == 'tree': trees.append(pts) elif kind == 'lot': lots.append(pts) return {'buildings': buildings, 'trees': trees, 'lots': lots} def segment_image_opencv(img_bgr, min_x, max_x, min_y, max_y): """OpenCV Canny + contours + classify. Returns { buildings, trees, lots }. Uses RETR_EXTERNAL (outer contours only) and approxPolyDP (perimeter-scaled) from github.com/jydhasan/google_map_trace for cleaner building outlines. """ gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) lo, hi = blurred.min(), blurred.max() if hi > lo: blurred = ((blurred.astype(float) - lo) / (hi - lo) * 255).astype(np.uint8) edges = cv2.Canny(blurred, 50, 150) contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) return _contours_to_result(contours, img_bgr, min_x, max_x, min_y, max_y) def segment_image_threshold(img_bgr, min_x, max_x, min_y, max_y, brightness=0, contrast=1.0, threshold_black=160, threshold_white=255): """NYPL map-vectorizer style: brightness + contrast then threshold to binary (dark = features). Good for line-drawing or high-contrast maps. Dark pixels (below threshold_black) become foreground; contour extraction and classification same as Canny path. See https://github.com/nypl-spacetime/map-vectorizer """ gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) # Brightness = add constant; contrast = multiply (GIMP-style) prep = (blurred.astype(np.float32) * contrast + brightness).clip(0, 255).astype(np.uint8) # Dark pixels (lines/features) -> white (255) so findContours gets them as foreground _, binary = cv2.threshold(prep, threshold_black, 255, cv2.THRESH_BINARY_INV) contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) return _contours_to_result(contours, img_bgr, min_x, max_x, min_y, max_y) def _parse_svg_path_d_to_polygons(d_string): """Parse SVG path 'd' attribute; return list of polygons as [(x,y), ...] in pixel space. Handles M, L, Z (absolute coords only). """ if not d_string or not d_string.strip(): return [] polygons = [] tokens = re.findall(r'[MLHVCSQTAZ]|-?\d*\.?\d+(?:[eE][-+]?\d+)?', d_string) i = 0 points = [] while i < len(tokens): t = tokens[i] if t.upper() in 'MLHVCSQTAZ': cmd = t.upper() i += 1 if cmd == 'M': if points and len(points) >= 3: polygons.append(points) points = [] if i + 2 <= len(tokens): try: points.append((float(tokens[i]), float(tokens[i + 1]))) i += 2 except ValueError: pass elif cmd == 'L': while i + 2 <= len(tokens) and tokens[i] not in 'MLHVCSQTAZ': try: points.append((float(tokens[i]), float(tokens[i + 1]))) i += 2 except ValueError: break elif cmd == 'Z': if points and len(points) >= 3: polygons.append(points) points = [] else: pass # skip H V C S Q T A for now else: i += 1 if points and len(points) >= 3: polygons.append(points) return polygons def segment_image_vtracer(img_bgr, min_x, max_x, min_y, max_y): """Vectorize with VTracer (raster to SVG), parse paths, convert to world, classify. Uses binary/line-art mode and filter_speckle for cleaner building outlines. """ import vtracer h, w = img_bgr.shape[:2] _, buf = cv2.imencode('.png', img_bgr) img_bytes = buf.tobytes() try: # colormode='binary' for line-art; filter_speckle to drop small shapes (cars, noise) svg_str = vtracer.convert_raw_image_to_svg( img_bytes, img_format='png', colormode='binary', filter_speckle=4, mode='polygon', ) except Exception as e: raise RuntimeError('VTracer conversion failed: ' + str(e)) if not svg_str or '= 4: vw, vh = float(parts[2]), float(parts[3]) else: vw, vh = w, h else: vw, vh = float(root.get('width', w)), float(root.get('height', h)) scale_x = (max_x - min_x) / vw if vw else 1.0 scale_y = (max_y - min_y) / vh if vh else 1.0 buildings = [] trees = [] lots = [] for path_el in root.iter(): if 'path' not in path_el.tag: continue d = path_el.get('d') if not d: continue for poly_px in _parse_svg_path_d_to_polygons(d): if len(poly_px) < 3: continue pts = [] for px, py in poly_px: x = min_x + (px / vw) * (max_x - min_x) y = max_y - (py / vh) * (max_y - min_y) pts.append({'x': round(x, 4), 'y': round(y, 4)}) if polygon_area_world(pts) < 15: continue kind = classify_contour(pts) if kind == 'building': buildings.append(pts) elif kind == 'tree': trees.append(pts) elif kind == 'lot': lots.append(pts) return {'buildings': buildings, 'trees': trees, 'lots': lots} def _parse_float_form(key, default): v = request.form.get(key) if v is None or v == '': return default try: return float(v) except (TypeError, ValueError): return default @app.route('/segment', methods=['POST']) def segment(): use_vtracer = os.environ.get('USE_VTRACER', '').lower() in ('1', 'true', 'yes') use_vtracer = use_vtracer or (request.form.get('useVtracer', '').lower() in ('1', 'true', 'yes')) use_threshold = request.form.get('useThreshold', '').lower() in ('1', 'true', 'yes') if use_vtracer and HAS_VTRACER: backend = 'vtracer' elif use_threshold and HAS_OPENCV: backend = 'threshold' elif HAS_OPENCV: backend = 'opencv' else: return jsonify({'error': 'OpenCV not installed. pip install opencv-python-headless numpy'}), 503 if use_vtracer and not HAS_VTRACER: return jsonify({'error': 'USE_VTRACER requested but vtracer not installed. pip install vtracer'}), 503 f = request.files.get('image') if not f: return jsonify({'error': 'Missing image file'}), 400 try: min_x = float(request.form.get('minX', 0)) max_x = float(request.form.get('maxX', 0)) min_y = float(request.form.get('minY', 0)) max_y = float(request.form.get('maxY', 0)) except (TypeError, ValueError): return jsonify({'error': 'Invalid extent (minX, maxX, minY, maxY)'}), 400 try: buf = f.read() nparr = np.frombuffer(buf, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) if img is None: return jsonify({'error': 'Could not decode image'}), 400 if backend == 'vtracer': result = segment_image_vtracer(img, min_x, max_x, min_y, max_y) elif backend == 'threshold': brightness = _parse_float_form('brightness', 0) contrast = _parse_float_form('contrast', 1.0) thresh_black = _parse_float_form('thresholdBlack', 160) thresh_white = _parse_float_form('thresholdWhite', 255) result = segment_image_threshold( img, min_x, max_x, min_y, max_y, brightness=brightness, contrast=contrast, threshold_black=int(thresh_black), threshold_white=int(thresh_white)) else: result = segment_image_opencv(img, min_x, max_x, min_y, max_y) return jsonify(result) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/health', methods=['GET']) def health(): return jsonify({'ok': True, 'opencv': HAS_OPENCV, 'vtracer': HAS_VTRACER}) if __name__ == '__main__': port = int(os.environ.get('ML_PORT', 3457)) app.run(host='127.0.0.1', port=port, threaded=True)