"""Bounded paint observations -> editable primitives and catalog instances. No map, annotation, street name, or world position is a recognition feature. Fit scores measure agreement, not calibrated semantic confidence. Unsupported observations stay unresolved; raw contours are never an output fallback. """ import json import math from dataclasses import asdict, dataclass import numpy as np from paint_geometry import digest, vectorize from scipy.ndimage import binary_closing from scipy.optimize import minimize from shapely import affinity, intersects_xy from shapely.geometry import LineString, Polygon, box, mapping, shape from shapely.ops import transform, unary_union from shapely.strtree import STRtree @dataclass(frozen=True) class Policy: min_area_m2: float = 0.035 min_length_m: float = 0.35 min_width_m: float = 0.06 max_strip_width_m: float = 1.0 rectangle_fill: float = 0.72 shape_tolerance_m: float = 0.06 min_symbol_score: float = 0.68 min_symbol_precision: float = 0.65 min_symbol_recall: float = 0.65 min_class_margin: float = 0.035 min_luminance_contrast: float = 0.025 max_candidates: int = 512 max_symbol_fits: int = 48 max_strip_hole_fraction: float = 0.10 min_unanchored_wear_length_m: float = 3.0 def parts(geometry): return [geometry] if geometry.geom_type == "Polygon" else list(geometry.geoms) def rectangle(geometry): q = np.asarray(geometry.minimum_rotated_rectangle.exterior.coords)[:4, :2] edges = np.roll(q, -1, axis=0) - q lengths = np.linalg.norm(edges, axis=1) i = int(np.argmax(lengths)) u = edges[i] / lengths[i] return q.mean(0), float(math.atan2(u[1], u[0])), float(max(lengths)), float(min(lengths)) def strip_geometry(centerline, width): return LineString(centerline).buffer(width / 2, cap_style=2, join_style=2) def catalog_geometry(template, center, angle, scale): g = unary_union([Polygon(p[0], p[1:]) for p in template["polygons"]]) lo, bottom, hi, top = g.bounds g = affinity.translate(g, -(lo + hi) / 2, -(bottom + top) / 2) g = affinity.scale(g, xfact=scale, yfact=scale, origin=(0, 0)) g = affinity.rotate(g, angle, origin=(0, 0), use_radians=True) return affinity.translate(g, *center) def reconstruct(obj, catalog): """Regenerate product geometry from compact parameters, never raw vertices.""" p = obj["parameters"] if obj["representation"] == "strip": return strip_geometry(p["centerline"], p["width_m"]) template = next(t for t in catalog["templates"] if t["id"] == p["template_id"]) return catalog_geometry(template, p["center"], p["angle_radians"], p["scale"]) def agreement(observed, fitted, tolerance, *, observed_buffer=None): # Pure geometry reuse: identical observed polygon and tolerance throughout a fit. buffered = observed.buffer(tolerance) if observed_buffer is None else observed_buffer precision = fitted.intersection(buffered).area / max(fitted.area, 1e-9) recall = observed.intersection(fitted.buffer(tolerance)).area / max(observed.area, 1e-9) overlap = observed.intersection(fitted).area / max(observed.union(fitted).area, 1e-9) f1 = 2 * precision * recall / max(precision + recall, 1e-9) return dict(precision=precision, recall=recall, overlap=overlap, score=0.6 * f1 + 0.4 * overlap) def contrast(geometry, rgb, matrix): """Local RGB evidence, not a claim that all bright rectangles are road paint.""" a, b, d, e, x0, y0 = matrix inverse = np.linalg.inv([[a, b], [d, e]]) q = np.asarray(geometry.envelope.exterior.coords)[:, :2] uv = (q - [x0, y0]) @ inverse.T padding = int(math.ceil(0.18 / min(np.hypot(a, d), np.hypot(b, e)))) + 2 left, top = np.maximum(np.floor(uv.min(0)).astype(int) - padding, 0) right, bottom = np.minimum(np.ceil(uv.max(0)).astype(int) + padding, rgb.shape[1::-1]) if right <= left or bottom <= top: return None yy, xx = np.mgrid[top:bottom, left:right] X = a * (xx + 0.5) + b * (yy + 0.5) + x0 Y = d * (xx + 0.5) + e * (yy + 0.5) + y0 inside = intersects_xy(geometry, X, Y) outside = intersects_xy(geometry.buffer(0.18).difference(geometry.buffer(0.06)), X, Y) if inside.sum() < 4 or outside.sum() < 4: return None lum = rgb[top:bottom, left:right].astype(float).mean(axis=2) / 255 return float(np.median(lum[inside]) - np.median(lum[outside])) def fit_strip(p, policy): center, angle, length, width = rectangle(p) if length < policy.min_length_m or width < policy.min_width_m: return None # Wear is a shape hypothesis only: retain the original observation for all # agreement checks. Large/elongated negative spaces remain real structure. shell = Polygon(p.exterior) if p.interiors and ( (shell.area - p.area) / max(shell.area, 1e-9) > policy.max_strip_hole_fraction or any(rectangle(Polygon(h))[2] > width for h in p.interiors) ): return None u = np.array([math.cos(angle), math.sin(angle)]) if ( width <= policy.max_strip_width_m and length / width >= 3 and p.area / (length * width) >= policy.rectangle_fill ): line = [center - u * length / 2, center + u * length / 2] return dict(centerline=np.asarray(line).tolist(), width_m=width) # Reuse the existing centreline/cross-section approach. Explicit refusal # replaces its historical raw-polygon fallback; real bends need few knots. if length < 1.5 or length / max(width, 0.01) < 3: return None n = np.array([-u[1], u[0]]) stations = np.linspace( -length / 2 + 0.03, length / 2 - 0.03, max(8, min(256, int(length / 0.10))) ) centers, widths = [], [] for t in stations: cross = shell.intersection( LineString(center + t * u + np.array([-width - 1, width + 1])[:, None] * n) ) if cross.geom_type != "LineString" or cross.length < 0.025: continue centers.append(cross.interpolate(0.5, normalized=True).coords[0][:2]) widths.append(cross.length) if len(centers) < max(8, 0.9 * len(stations)): return None points = np.asarray(centers) tangent = np.gradient(points, axis=0) tangent /= np.maximum(np.linalg.norm(tangent, axis=1)[:, None], 1e-9) widths = np.asarray(widths) * np.abs(tangent @ u) w = float(np.median(widths)) if not policy.min_width_m <= w <= 0.65: return None variable_width = np.ptp(np.quantile(widths, [0.1, 0.9])) > 0.5 * w # Prefer a rectangle when the observed strip supports one. Boundary nicks # must not force needless bends into an otherwise straight crossing bar. offset = float(np.median((points - center) @ n)) straight = [center + offset * n - u * length / 2, center + offset * n + u * length / 2] rectangle_fit = strip_geometry(straight, w) if ( (not variable_width or length >= policy.min_unanchored_wear_length_m) and agreement(p, rectangle_fit, policy.shape_tolerance_m)["score"] >= 0.78 and p.hausdorff_distance(rectangle_fit) <= 0.25 ): return dict(centerline=np.asarray(straight).tolist(), width_m=w) # A worn straight stripe can have variable cross-sections while its full # rectangular explanation is strong. Width consistency constrains the bent # fallback, not the already verified straight candidate above. if variable_width: return None line = LineString(points).simplify(policy.shape_tolerance_m) if not line.is_simple or len(line.coords) > 12: return None g = strip_geometry(list(line.coords), w) if agreement(p, g, policy.shape_tolerance_m)["score"] < 0.78 or p.hausdorff_distance(g) > 0.25: return None return dict(centerline=[list(q) for q in line.coords], width_m=w) def fit_junction_strips(p, policy): """Explain thin, near-orthogonal junctions with a few observed rectangles. Long boundary directions propose axes, not coordinates or road rules. Require local support for every arm AND agreement of the complete union. A shaft alone cannot explain a missing arrow head or other residual shape. """ if p.area < .3 or len(p.interiors) > 8: return [] _, _, length, width = rectangle(p) if width < 1 or p.area / max(length * width, 1e-9) > .6: return [] q = np.asarray(p.simplify(.08, preserve_topology=True).exterior.coords)[:, :2] edges = np.diff(q, axis=0) modes = [] for v in sorted(edges, key=lambda v: -float(np.linalg.norm(v))): length = float(np.linalg.norm(v)) if length < 1.5: continue u = v / length if not any(abs(u @ old) > math.cos(math.radians(10)) for old in modes): modes.append(u) if len(modes) == 4: break pairs = [(u, v) for i, u in enumerate(modes) for v in modes[i+1:] if abs(u @ v) < math.sin(math.radians(10))] if not pairs: return [] for axes in pairs: proposals = [] directions = [] for axis_index, u in enumerate(axes): n = np.array([-u[1], u[0]]) coords = np.asarray(p.exterior.coords)[:, :2] along, across = coords @ u, coords @ n low, high = float(along.min()), float(along.max()) count = max(20, min(512, int((high-low)/.08))) step = (high-low) / count samples = [] for t in np.linspace(low+step/2, high-step/2, count): cross = p.intersection(LineString([u*t+n*(across.min()-1), u*t+n*(across.max()+1)])) segments = ([cross] if cross.geom_type == "LineString" else getattr(cross, "geoms", [])) for segment in segments: if (segment.geom_type != "LineString" or not policy.min_width_m <= segment.length <= .65): continue mid = np.asarray(segment.interpolate(.5, normalized=True).coords[0])[:2] samples.append((float(mid @ n), t, segment.length)) samples.sort() clusters = [] for sample in samples: if not clusters or sample[0]-clusters[-1][-1][0] > .10: clusters.append([]) clusters[-1].append(sample) for cluster in clusters: c = np.asarray(cluster) if len(c) < 16: continue offset, width = float(np.median(c[:, 0])), float(np.median(c[:, 2])) if np.ptp(np.quantile(c[:, 0], [.1,.9])) > width/2: continue ordered = c[np.argsort(c[:, 1])] # A wide junction may omit a few cross-sections, not a real gap. splits = np.where(np.diff(ordered[:, 1]) > max(.25, 2*width))[0]+1 for run in np.split(ordered, splits): lo, hi = float(run[:,1].min()-step/2), float(run[:,1].max()+step/2) if len(run) < 16 or hi-lo < 1.5 or hi-lo < 4*width: continue line = [u*lo+n*offset, u*hi+n*offset] fitted = strip_geometry(line,width) holes = [Polygon(h) for h in p.interiors if Polygon(h).intersects(fitted)] if (any(rectangle(h)[2] > width for h in holes) or sum(h.intersection(fitted).area for h in holes) > policy.max_strip_hole_fraction * fitted.area): continue # Every interior longitudinal interval needs observed paint. # A wide junction has support; a true gap stays an interval # gap even when the enclosing component is connected elsewhere. intervals = [] for piece in parts(p.intersection(fitted)): if piece.geom_type == "Polygon" and piece.area > 0: projections = np.asarray(piece.exterior.coords)[:, :2] @ u intervals.append((float(projections.min()),float(projections.max()))) end = lo+step continuous = True for begin, finish in sorted(intervals): if finish < end: continue if begin > end+1e-6: continuous = False break end = max(end,finish) if not continuous or end < hi-step: continue if fitted.intersection(p).area/fitted.area < .70: continue local = p.intersection(fitted.buffer(policy.shape_tolerance_m)) if agreement(local,fitted,policy.shape_tolerance_m)["score"] < .78: continue proposals.append(dict(centerline=np.asarray(line).tolist(),width_m=width)) directions.append(axis_index) if not 2 <= len(proposals) <= 4 or len(set(directions)) != 2: continue shapes = [strip_geometry(x["centerline"],x["width_m"]) for x in proposals] fitted = unary_union(shapes) if not fitted.is_valid or not all(any(i != j and a.intersects(b.buffer(.08)) for j,b in enumerate(shapes)) for i,a in enumerate(shapes)): continue metrics = agreement(p,fitted,policy.shape_tolerance_m) if (metrics["score"] >= .78 and metrics["recall"] >= .90 and metrics["precision"] >= .85 and p.hausdorff_distance(fitted) <= .25): return proposals return [] def fit_strips(p, policy): params = fit_strip(p, policy) return [params] if params is not None else fit_junction_strips(p, policy) def fit_symbol(p, templates, policy, budget): center, angle, length, width = rectangle(p) if not (0.6 < length < 9 and 0.25 < width < 4 and 0.07 < p.area / (length * width) < 0.8): return None, "not-symbol-shaped" observed_buffer = p.buffer(policy.shape_tolerance_m) def metrics_for(g): return agreement(p, g, policy.shape_tolerance_m, observed_buffer=observed_buffer) hypotheses = [] for template in templates: base = catalog_geometry(template, [0, 0], 0, 1) _, _, L, W = rectangle(base) if not 0.65 < (length / width) / (L / W) < 1.5: continue scale = math.sqrt(length * width / (L * W)) for flip in (0, math.pi): x0 = [center[0], center[1], angle + flip, scale] g = catalog_geometry(template, x0[:2], x0[2], x0[3]) score = metrics_for(g)["score"] hypotheses.append((score, template, x0)) # Bound optimization work per frame and per object, including bad inputs. fits = [] for initial, template, x0 in sorted(hypotheses, key=lambda h: -h[0])[:4]: if initial < 0.35: continue if budget[0] >= policy.max_symbol_fits: return None, "symbol-fit-budget" budget[0] += 1 bounds = [ (x0[0] - 0.25, x0[0] + 0.25), (x0[1] - 0.25, x0[1] + 0.25), (x0[2] - 0.20, x0[2] + 0.20), (x0[3] * 0.8, x0[3] * 1.2), ] def objective(x, template=template): return 1 - metrics_for(catalog_geometry(template, x[:2], x[2], x[3]))["score"] result = minimize( objective, x0, method="Powell", bounds=bounds, options=dict(maxiter=12, maxfev=240, xtol=0.002, ftol=0.002), ) # The initial candidate remains admissible when the bounded optimizer # terminates early; the final measured evidence gates still apply. x = result.x if result.fun < objective(x0) else x0 g = catalog_geometry(template, x[:2], x[2], x[3]) metrics = metrics_for(g) fits.append((metrics["score"], template, list(x), metrics)) fits.sort(key=lambda f: -f[0]) if not fits: return None, "no-template-supported" _, template, x, metrics = fits[0] runner = next((f[0] for f in fits[1:] if f[1]["id"] != template["id"]), 0) if ( metrics["score"] < policy.min_symbol_score or metrics["precision"] < policy.min_symbol_precision or metrics["recall"] < policy.min_symbol_recall ): return None, "insufficient-template-support" if metrics["score"] - runner < policy.min_class_margin: return None, "ambiguous-template-class" g = catalog_geometry(template, x[:2], x[2], x[3]) holes = unary_union([Polygon(h) for part in parts(g) for h in part.interiors]) if not holes.is_empty and holes.intersection(p).area / max(holes.area, 1e-9) > 0.25: return None, "template-negative-space-conflict" params = dict(template_id=template["id"], center=x[:2], angle_radians=x[2], scale=x[3]) return (params, metrics), None def arbitrate_symbol(observed, fitted, policy, *, center, angle, rgb, pixel_to_scene): """Compare on identical evidence; every local template part needs actual paint. The 3x3 partition lives in the fitted template frame, never scene coordinates. Local precision permits at most half a native pixel diagonal of uncertainty. Each part also needs an unbuffered witness, so that uncertainty cannot conceal a wholly absent small arrowhead. Existing global tolerance remains unchanged. No per-class, per-scale, per-location, or learned acceptance threshold is used. """ local = affinity.rotate( affinity.translate(fitted, -center[0], -center[1]), -angle, origin=(0, 0), use_radians=True, ) xs = np.linspace(local.bounds[0], local.bounds[2], 4) ys = np.linspace(local.bounds[1], local.bounds[3], 4) a, b, d, e, _, _ = pixel_to_scene pixel_radius = 0.5 * max(np.hypot(a + b, d + e), np.hypot(a - b, d - e)) local_tolerance = min(policy.shape_tolerance_m, pixel_radius) # Intersect in the normalized frame: rotating clipped fragments back into # world space can create degenerate hole/shell contacts through roundoff. local_observed = affinity.rotate( affinity.translate(observed, -center[0], -center[1]), -angle, origin=(0, 0), use_radians=True, ) supported = local_observed.buffer(local_tolerance) support = [] for iy in range(3): for ix in range(3): piece = local.intersection(box(xs[ix], ys[iy], xs[ix + 1], ys[iy + 1])) if piece.area <= 1e-12: continue support.append( dict(cell=[ix, iy], area_m2=piece.area, precision=piece.intersection(supported).area / piece.area, unbuffered_precision=piece.intersection(local_observed).area / piece.area) ) strips = [] for component in parts(observed): params = fit_strip(component, policy) if component.area >= policy.min_area_m2 else None if params is None: continue g = strip_geometry(params["centerline"], params["width_m"]) delta = contrast(g, rgb, pixel_to_scene) if delta is not None and delta >= policy.min_luminance_contrast: strips.append(g) symbol_score = agreement(observed, fitted, policy.shape_tolerance_m)["score"] competitor = ( agreement(observed, unary_union(strips), policy.shape_tolerance_m) if strips else None ) audit = dict( template_partition="3x3-in-template-frame", local_support_buffer_m=local_tolerance, unbuffered_witness_required=True, min_required_precision=policy.min_symbol_precision, parts=support, symbol_score=symbol_score, strip_competitor=competitor, min_required_margin=policy.min_class_margin, ) if not support or any( p["precision"] < policy.min_symbol_precision or p["unbuffered_precision"] <= 1e-12 for p in support ): return audit, "unsupported-template-part" if competitor is not None and symbol_score - competitor["score"] < policy.min_class_margin: return audit, "strip-competitor-not-beaten" return audit, None def crosswalk_groups(objects): """Deterministic groups of independent, parallel observed bars. Compare direction/length against an anchor, not a transitive angle chain. Overlapping windows of one bar cannot supply independent votes. """ bars = [] for obj in sorted(objects, key=lambda o: o["id"]): if obj["representation"] != "strip" or len(obj["parameters"]["centerline"]) != 2: continue p = obj["parameters"] q = np.asarray(p["centerline"]) length = np.linalg.norm(q[1] - q[0]) if 0.28 <= p["width_m"] <= 1 and 1.5 <= length <= 8: bars.append((obj, q.mean(0), (q[1] - q[0]) / length, length)) remaining = set(range(len(bars))) groups = [] while remaining: seed = min(remaining) remaining.remove(seed) first, center, u, length = bars[seed] n = np.array([-u[1], u[0]]) aligned = [seed] + [j for j in sorted(remaining) if abs(u @ bars[j][2]) > math.cos(math.radians(8)) and abs((bars[j][1] - center) @ u) < 0.5 and 0.8 < bars[j][3] / length < 1.25 and 0.7 < bars[j][0]["parameters"]["width_m"] / first["parameters"]["width_m"] < 1.43] aligned.sort(key=lambda j: float(bars[j][1] @ n)) clusters, current = [], [] for j in aligned: if current and float((bars[j][1] - bars[current[-1]][1]) @ n) > 2 + 1e-6: clusters.append(current) current = [] # Duplicate support or nearly coincident bars never count twice. if current and (float((bars[j][1] - bars[current[-1]][1]) @ n) <= .45 or any(set(bars[j][0]["observation_ids"]) & set(bars[i][0]["observation_ids"]) for i in current)): continue current.append(j) if current: clusters.append(current) for cluster in clusters: if len(cluster) < 3: continue offsets = np.array([bars[j][1] @ n for j in cluster]) gaps = np.diff(offsets) step = float(np.median(gaps[gaps <= np.median(gaps)])) multiples = np.maximum(1, np.rint(gaps / step)) if (multiples > 2).any() or (np.abs(gaps - multiples * step) > .18 * step).any(): continue remaining.difference_update(cluster) groups.append(dict(bars=[bars[j] for j in cluster], direction=u, normal=n, step_m=step, offsets=offsets)) return groups def group_crosswalks(objects): """Classify actual bars after reconciliation; no fixed six-bar template.""" for obj in objects: for key in ("group_id", "observed_bar_count", "crosswalk_parameters"): obj.pop(key, None) if obj["kind"] == "crosswalk_bar": obj["kind"] = "linear_marking" for group in crosswalk_groups(objects): bars = group["bars"] gid = "crossing-" + digest(sorted(b[0]["id"] for b in bars))[:20] parameters = dict(direction=group["direction"].tolist(), step_m=group["step_m"], median_width_m=float(np.median( [b[0]["parameters"]["width_m"] for b in bars])), median_length_m=float(np.median([b[3] for b in bars]))) for obj, *_ in bars: obj.update(kind="crosswalk_bar", group_id=gid, observed_bar_count=len(bars), crosswalk_parameters=parameters) def recover_crosswalks(objects, observations, *, rgb, pixel_to_scene, policy): """Recheck rejected observations in an independently supported group frame. No synthetic slots: a candidate needs its own area, full observed extent, width, bounded holes, whole-shape agreement and RGB contrast. Recovered candidates do not seed further recovery in this pass. """ groups = crosswalk_groups(objects) used = {i for o in objects for i in o["observation_ids"]} recovered = [] for feature in sorted(observations, key=lambda f: f["id"]): if feature["id"] in used: continue p = shape(feature["geometry"]) if p.area < policy.min_area_m2: continue for group in groups: u, n, bars = group["direction"], group["normal"], group["bars"] q = np.asarray(p.exterior.coords)[:, :2] along, across = q @ u, q @ n lo, hi = float(along.min()), float(along.max()) mid = float((across.min() + across.max()) / 2) length = hi - lo width = float(np.median([b[0]["parameters"]["width_m"] for b in bars])) reference_length = float(np.median([b[3] for b in bars])) offsets, step = group["offsets"], group["step_m"] # Only observed intervals near the demonstrated sequence, never # arbitrary continuation or a tiny spot promoted to a full bar. if not (offsets.min() - step * 1.18 <= mid <= offsets.max() + step * 1.18 and .8 < length / reference_length < 1.25 and .7 < p.area / max(length * width, 1e-9) < 1.43 and np.min(np.abs(offsets - mid)) > .45 and abs((mid - offsets[0]) / step - round((mid - offsets[0]) / step)) <= .18 and abs((lo + hi) / 2 - np.median([b[1] @ u for b in bars])) < .5): continue shell = Polygon(p.exterior) if p.interiors and ((shell.area - p.area) / shell.area > policy.max_strip_hole_fraction or any(rectangle(Polygon(h))[2] > min(width, rectangle(p)[3]) for h in p.interiors)): continue line = [u * lo + n * mid, u * hi + n * mid] fitted = strip_geometry(line, width) metrics = agreement(p, fitted, policy.shape_tolerance_m) if metrics["score"] < .78 or p.hausdorff_distance(fitted) > .25: continue delta = contrast(fitted, rgb, pixel_to_scene) if delta is None or delta < policy.min_luminance_contrast: continue obj = dict(representation="strip", kind="linear_marking", parameters=dict(centerline=np.asarray(line).tolist(), width_m=width), observation_ids=[feature["id"]], fit=metrics, luminance_contrast=delta, support_boundary=feature["properties"]["support_boundary"], recovery=dict(method="observed-crosswalk-group", seed_ids=sorted(b[0]["id"] for b in bars), slot=int(round((mid-offsets[0])/step)))) obj["id"] = "object-" + digest(obj)[:24] recovered.append(obj) used.add(feature["id"]) break conflicts = set() for i,a in enumerate(recovered): ga = strip_geometry(a["parameters"]["centerline"],a["parameters"]["width_m"]) for j,b in enumerate(recovered[:i]): same_slot = (a["recovery"]["seed_ids"] == b["recovery"]["seed_ids"] and a["recovery"]["slot"] == b["recovery"]["slot"]) gb = strip_geometry(b["parameters"]["centerline"],b["parameters"]["width_m"]) if same_slot or ga.intersection(gb).area > 1e-6: conflicts.update((i,j)) return [o for i,o in enumerate(recovered) if i not in conflicts] def assemble(mask, rgb, *, pixel_to_scene, source_id, catalog, policy=None): policy = policy or Policy() mask = np.asarray(mask) rgb = np.asarray(rgb) if mask.ndim != 2 or mask.dtype.kind not in "biu" or not np.isin(mask, [0, 1]).all(): raise ValueError("Binary automatic prediction required; targets/unknown are not inputs") if rgb.shape != mask.shape + (3,) or rgb.dtype != np.uint8: raise ValueError("Matching uint8 RGB evidence required") raw = vectorize(mask, pixel_to_scene=pixel_to_scene, source_id=source_id) if len(raw["features"]) > policy.max_candidates: raise ValueError("Candidate budget exceeded") catalog_sha = digest(catalog) templates = [ t for t in catalog["templates"] if not t.get("hidden") and t["id"] not in ("linear_marking", "zebra") ] objects, rejected, budget = [], [], [0] # Only symbol proposals may join small wear gaps. Strip intervals use the # original components so neighboring dashes are not closed into one line. cell = min( np.linalg.norm(np.asarray(pixel_to_scene)[[0, 2]]), np.linalg.norm(np.asarray(pixel_to_scene)[[1, 3]]), ) radius = max(1, min(8, int(round(0.04 / cell)))) closed = binary_closing(mask, iterations=radius, border_value=0) proposals = vectorize( closed.astype(np.uint8), pixel_to_scene=pixel_to_scene, source_id=source_id + "-symbol-proposals", ) raw_geometries = [shape(r["geometry"]) for r in raw["features"]] spatial = STRtree(raw_geometries) consumed = set() for f in sorted(proposals["features"], key=lambda f: -shape(f["geometry"]).area): p = shape(f["geometry"]) if p.area < 0.20: continue # Bounding-box pruning only; preserve original component order and predicate. members = [ raw["features"][i] for i in sorted(int(index) for index in spatial.query(p)) if raw_geometries[i].intersection(p).area > 0.5 * raw_geometries[i].area ] if not members: continue observed = unary_union([shape(r["geometry"]) for r in members]) # A component grouping is a hypothesis, not a replacement for evidence. result, reason = fit_symbol(observed, templates, policy, budget) if result is None: continue params, metrics = result g = catalog_geometry( next(t for t in templates if t["id"] == params["template_id"]), params["center"], params["angle_radians"], params["scale"], ) delta = contrast(g, rgb, pixel_to_scene) if delta is None or delta < policy.min_luminance_contrast: continue arbitration, reason = arbitrate_symbol( observed, g, policy, center=params["center"], angle=params["angle_radians"], rgb=rgb, pixel_to_scene=pixel_to_scene, ) if reason is not None: continue ids = sorted(r["id"] for r in members) obj = dict( representation="catalog", arbitration=arbitration, kind=params["template_id"], parameters=params, observation_ids=ids, fit=metrics, luminance_contrast=delta, ) obj["support_boundary"] = sorted( {flag for member in members for flag in member["properties"]["support_boundary"]} ) obj["id"] = "object-" + digest([raw["source_sha256"], catalog_sha, obj])[:24] objects.append(obj) consumed.update(ids) for f in raw["features"]: if f["id"] in consumed: continue p = shape(f["geometry"]) proposals = fit_strips(p, policy) if p.area >= policy.min_area_m2 else [] reason = "too-small" if p.area < policy.min_area_m2 else "unsupported-shape" candidates = [] for params in proposals: g = strip_geometry(params["centerline"], params["width_m"]) delta = contrast(g, rgb, pixel_to_scene) if delta is None or delta < policy.min_luminance_contrast: reason = "insufficient-rgb-contrast" break support = (p if len(proposals) == 1 else p.intersection(g.buffer(policy.shape_tolerance_m))) obj = dict(representation="strip", kind="linear_marking", parameters=params, observation_ids=[f["id"]], fit=agreement(support,g,policy.shape_tolerance_m), luminance_contrast=delta, support_boundary=f["properties"]["support_boundary"]) if len(proposals) > 1: obj["decomposition"] = "observed-orthogonal-junction" obj["id"] = "object-" + digest([raw["source_sha256"],obj])[:24] candidates.append(obj) if proposals and len(candidates) == len(proposals): objects.extend(candidates) continue rejected.append( dict(observation_id=f["id"], reason=reason, status="unresolved-not-background") ) recovered = recover_crosswalks(objects, raw["features"], rgb=rgb, pixel_to_scene=pixel_to_scene, policy=policy) recovered_ids = {i for o in recovered for i in o["observation_ids"]} rejected = [r for r in rejected if r["observation_id"] not in recovered_ids] objects.extend(recovered) group_crosswalks(objects) for obj in objects: obj["instance_completeness"] = "not-assessed" obj["geometry"] = mapping(reconstruct(obj, catalog)) return dict( schema="missioncore.paint-objects/v1", source=raw["source"], catalog_sha256=catalog_sha, policy=asdict(policy), objects=objects, rejected=rejected, symbol_fits=budget[0], raw_components=len(raw["features"]), labels_used=False, human_geometry_used=False, ) def surface_plane(obj, *, depth, alpha, camera_eye_z, pixel_to_scene, catalog): """Fit observed interior surface, then place a compact object on that plane. This is Gaussian-derived placement, not surveyed height. No zero-height or camera-target fallback. Unreliable support preserves the entire 2-D object. """ return surface_geometry_plane( reconstruct(obj, catalog), depth=depth, alpha=alpha, camera_eye_z=camera_eye_z, pixel_to_scene=pixel_to_scene, ) def surface_geometry_plane(g, *, depth, alpha, camera_eye_z, pixel_to_scene): """Observed surface estimate for arbitrary geometry, without catalog input.""" depth, alpha = np.asarray(depth), np.asarray(alpha) if ( depth.ndim != 2 or alpha.shape != depth.shape or not np.isfinite(camera_eye_z) or not np.isfinite(pixel_to_scene).all() ): raise ValueError("Invalid surface inputs") a, b, d, e, x0, y0 = pixel_to_scene yy, xx = np.indices(depth.shape) X = a * (xx + 0.5) + b * (yy + 0.5) + x0 Y = d * (xx + 0.5) + e * (yy + 0.5) + y0 support = ( intersects_xy(g, X, Y) & np.isfinite(depth) & (depth > 0) & np.isfinite(alpha) & (alpha >= 0.95) ) if support.sum() < 24: return None, dict(reason="insufficient-surface-support", samples=int(support.sum())) xy = np.column_stack([X[support], Y[support]]) z = camera_eye_z - depth[support] stride = max(1, math.ceil(len(xy) / 4096)) xy = xy[::stride] z = z[::stride] origin = xy.mean(0) design = np.column_stack([xy - origin, np.ones(len(xy))]) keep = np.ones(len(xy), bool) for _ in range(4): coeff = np.linalg.lstsq(design[keep], z[keep], rcond=None)[0] residual = np.abs(design @ coeff - z) keep = residual <= max(0.03, 3 * np.median(residual)) if keep.sum() < 24: return None, dict(reason="unstable-surface-fit") center, angle, length, width = rectangle(g) u = np.array([math.cos(angle), math.sin(angle)]) n = np.array([-u[1], u[0]]) q = xy[keep] spans = [float(np.ptp(q @ u) / length), float(np.ptp(q @ n) / width)] p95 = float(np.quantile(np.abs(design[keep] @ coeff - z[keep]), 0.95)) info = dict( samples=int(keep.sum()), support_spans=spans, residual_p95_m=p95, slopes=coeff[:2].tolist(), origin=origin.tolist(), intercept=float(coeff[2]), source="gaussian-interior-plane", survey_verified=False, ) if min(spans) < 0.7 or p95 > 0.15 or np.linalg.norm(coeff[:2]) > 0.5 or keep.mean() < 0.6: return None, dict(info, reason="unreliable-surface-fit") def height(x, y): return ( coeff[0] * (np.asarray(x) - origin[0]) + coeff[1] * (np.asarray(y) - origin[1]) + coeff[2] ) return height, info def editor_features(obj, *, catalog, height, surface, height_source, observation_source): """Materialize an immutable automatic proposal for the existing editor. Editable geometry is authoritative after a user operation. Recognition parameters are explicitly an immutable SOURCE snapshot, never current editable parameters or a reconstruction command for a human revision. """ if height is None: return [] g = transform(lambda x, y, z=None: (x, y, height(x, y)), reconstruct(obj, catalog)) coordinates = [q for p in parts(g) for ring in [p.exterior, *p.interiors] for q in ring.coords] if not np.isfinite(coordinates).all(): raise ValueError("Invalid materialized height") props = dict( subtype=obj["kind"], authority="observation-only", route_permission="unassigned", confidence=None, confidence_status="not-assessed", review_status="unreviewed", annotation_origin="automatic-primitive-assembly", method="catalog-and-strip-fit-v1", semantic_element_id=obj.get("group_id", obj["id"]), support_boundary=obj.get("support_boundary", []), instance_completeness="not-assessed", source_observation_sha256=observation_source, height_source=height_source, catalog_sha256=digest(catalog), recognition_snapshot=dict( role="immutable-automatic-source-not-current-edited-geometry", representation=obj["representation"], parameters=obj["parameters"], surface_model=surface, ), ) props["class"] = "road_marking" if obj["representation"] == "catalog": template = next( t for t in catalog["templates"] if t["id"] == obj["parameters"]["template_id"] ) props.update(template_id=template["id"], template_source=template.get("source")) if "observed_bar_count" in obj: props["observed_bar_count"] = obj["observed_bar_count"] features = [ dict(type="Feature", id=obj["id"] + "-" + str(i), geometry=mapping(p), properties=props) for i, p in enumerate(parts(g)) ] # Core's editing operations mutate coordinate lists. Return the actual JSON # contract even before disk serialization, with no shared caller metadata. return json.loads(json.dumps(features, allow_nan=False))