Files

282 lines
11 KiB
Python

"""Conservative second-pass strip admission using frozen strict automatic seeds.
Seeds are machine output from the SAME observations, never manual geometry.
New candidates cannot become seeds. Existing primitives are retained verbatim.
"""
import copy
import math
import numpy as np
import paint_objects as po
from paint_geometry import digest
from shapely.geometry import LineString, mapping, shape
from shapely.ops import unary_union
def strip_contrast(parameters, rgb, matrix):
"""Measure paint against EACH lateral flank; a bright-region edge is insufficient.
All samples belong to the novel fitted part. Missing flank coverage abstains.
Coordinates follow the same pixel-centre affine as observation extraction.
"""
q = np.asarray(parameters["centerline"], dtype=float)
if q.shape != (2, 2):
return None
u = q[1] - q[0]
length = np.linalg.norm(u)
if length < 0.35:
return None
u /= length
n = np.array([-u[1], u[0]])
half = float(parameters["width_m"]) / 2
a, b, d, e, x0, y0 = matrix
inverse = np.linalg.inv([[a, b], [d, e]])
corners = np.array([point + sign * (half + 0.18) * n for point in q for sign in [-1, 1]])
uv = (corners - [x0, y0]) @ inverse.T
left, top = np.floor(uv.min(0)).astype(int)
right, bottom = np.ceil(uv.max(0)).astype(int)
if left < 0 or top < 0 or right > rgb.shape[1] or bottom > rgb.shape[0]:
return None
yy, xx = np.mgrid[top:bottom, left:right]
X = a * (xx + 0.5) + b * (yy + 0.5) + x0 - q[0, 0]
Y = d * (xx + 0.5) + e * (yy + 0.5) + y0 - q[0, 1]
along = X * u[0] + Y * u[1]
across = X * n[0] + Y * n[1]
interior = (along > 0.05) & (along < length - 0.05)
masks = [
interior & (np.abs(across) < half),
interior & (across > half + 0.06) & (across < half + 0.18),
interior & (across < -half - 0.06) & (across > -half - 0.18),
]
if any(mask.sum() < 4 for mask in masks):
return None
lum = rgb[top:bottom, left:right].astype(float).mean(axis=2) / 255
values = [float(np.median(lum[mask])) for mask in masks]
contrasts = [values[0] - v for v in values[1:]]
return dict(
contrast=min(contrasts),
flank_contrasts=contrasts,
sample_counts=[int(m.sum()) for m in masks],
)
def line_relation(candidate, seed):
a = np.asarray(candidate["parameters"]["centerline"], dtype=float)
b = np.asarray(seed["parameters"]["centerline"], dtype=float)
if len(a) != 2 or len(b) != 2:
return False
u = a[1] - a[0]
v = b[1] - b[0]
length = np.linalg.norm(u)
other = np.linalg.norm(v)
if min(length, other) < 1e-6:
return False
u /= length
v /= other
if abs(u @ v) < math.cos(math.radians(5)):
return False
width = candidate["parameters"]["width_m"]
sw = seed["parameters"]["width_m"]
if not 0.75 <= width / sw <= 1.333:
return False
n = np.array([-v[1], v[0]])
if np.max(np.abs((a - b[0]) @ n)) > max(0.08, 0.5 * sw):
return False
# Classification may continue only the same observed paint, not a nearby
# parallel stripe or a chain across an unobserved interval.
observed = shape(candidate["observation_geometry"])
seed_observed = shape(seed["observation_geometry"])
if observed.intersection(seed_observed).area <= 1e-6:
return False
projected = (a - b[0]) @ v
return projected.min() < -0.1 or projected.max() > other + 0.1
def crosswalk_support(candidate, groups):
q = np.asarray(candidate["parameters"]["centerline"], dtype=float)
if len(q) != 2:
return []
length = np.linalg.norm(q[1] - q[0])
width = candidate["parameters"]["width_m"]
if length < 1e-6:
return []
direction = (q[1] - q[0]) / length
center = q.mean(0)
for g in groups:
bars = g["bars"]
u = g["direction"]
n = g["normal"]
offsets = g["offsets"]
step = g["step_m"]
if abs(direction @ u) < math.cos(math.radians(8)):
continue
if not 0.8 < length / np.median([b[3] for b in bars]) < 1.25:
continue
if not 0.7 < width / np.median([b[0]["parameters"]["width_m"] for b in bars]) < 1.43:
continue
if abs(center @ u - np.median([b[1] @ u for b in bars])) >= 0.5:
continue
across = center @ n
if not offsets.min() - step * 1.18 <= across <= offsets.max() + step * 1.18:
continue
if abs((across - offsets[0]) / step - round((across - offsets[0]) / step)) > 0.18:
continue
return [b[0]["id"] for b in bars]
return []
def contextual_additions(
strict_objects, candidates, *, contrast_fn, experimental_continuations=False
):
"""Return additions + decisions. Does not edit, replace or reclassify seeds.
Both input lists are automatically normalized proposals with RGB/surface
checks already performed. The qualified default only recovers observed
crosswalk bars. Continuation is an explicit research branch: geometric/RGB
checks cannot yet distinguish road paint from bright curbs reliably.
"""
seeds = [
o
for o in strict_objects
if o["placement_status"] == "placed" and o["representation"] == "strip"
]
catalog = [
shape(o["geometry"])
for o in strict_objects
if o["placement_status"] == "placed" and o["representation"] == "catalog"
]
groups = po.crosswalk_groups(seeds)
seed_by_id = {o["id"]: o for o in seeds}
occupied = unary_union(
[shape(o["geometry"]) for o in strict_objects if o["placement_status"] == "placed"]
)
additions = []
decisions = []
eligible = [
o
for o in candidates
if o["placement_status"] == "placed" and o["representation"] == "strip"
]
direct = {o["id"]: [s["id"] for s in seeds if line_relation(o, s)] for o in eligible}
junction_anchors = [o for o in eligible if direct[o["id"]] and o.get("junction_components")]
for original in sorted(candidates, key=lambda o: (-o["fit"]["score"], o["id"])):
if original["placement_status"] != "placed" or original["representation"] != "strip":
continue
q = np.asarray(original["parameters"]["centerline"], dtype=float)
if len(q) != 2:
continue
g = shape(original["geometry"])
if g.difference(occupied.buffer(0.04)).area < 0.05 * g.area:
continue
crossing = crosswalk_support(original, groups)
group_id = None
if crossing:
group_ids = {seed_by_id[i].get("group_id") for i in crossing}
if len(group_ids) != 1 or None in group_ids:
decisions.append(
dict(
id=original["id"], accepted=False, reason="ambiguous-strict-crosswalk-group"
)
)
continue
group_id = next(iter(group_ids))
supporting = direct[original["id"]]
junction = []
if not crossing and not supporting and original.get("junction_components"):
components = set(original["junction_components"])
for anchor in junction_anchors:
if (
components.intersection(anchor["junction_components"])
and shape(anchor["geometry"]).distance(g) <= 0.08
):
junction.extend(direct[anchor["id"]])
reason = (
"crosswalk-group"
if crossing
else "observed-continuation"
if supporting
else "anchored-junction"
if junction
else None
)
if reason is not None and reason != "crosswalk-group" and not experimental_continuations:
decisions.append(
dict(id=original["id"], accepted=False, reason="unqualified-continuation-disabled")
)
continue
if reason is None:
decisions.append(
dict(id=original["id"], accepted=False, reason="no-independent-strict-context")
)
continue
if any(g.intersection(c).area > 0.05 * g.area for c in catalog):
decisions.append(dict(id=original["id"], accepted=False, reason="catalog-conflict"))
continue
# Keep existing seed geometry exactly. Only the observed, non-overlapping
# part of a proposed continuation is added; never extend across a gap.
remaining = LineString(q).difference(occupied.buffer(0.02))
segments = (
[remaining]
if remaining.geom_type == "LineString"
else list(getattr(remaining, "geoms", []))
)
accepted = []
for segment in segments:
if segment.geom_type != "LineString" or segment.length < 0.35:
continue
params = dict(
centerline=[list(segment.coords[0]), list(segment.coords[-1])],
width_m=original["parameters"]["width_m"],
)
fitted = po.strip_geometry(params["centerline"], params["width_m"])
if fitted.difference(g.buffer(1e-8)).area > 1e-6:
continue
support = shape(original["observation_geometry"]).intersection(fitted.buffer(0.06))
if support.is_empty:
continue
metrics = po.agreement(support, fitted, 0.06)
immediate = support.intersection(fitted).area / fitted.area
if (
metrics["score"] < 0.78
or metrics["precision"] < 0.85
or metrics["recall"] < 0.85
or immediate < 0.70
):
continue
rgb = contrast_fn(original, fitted)
if rgb is None or rgb["contrast"] < po.Policy().min_luminance_contrast:
continue
o = copy.deepcopy(original)
for key in ("group_id", "observed_bar_count", "crosswalk_parameters"):
o.pop(key, None)
if crossing:
o["group_id"] = group_id
o["luminance_contrast"] = rgb["contrast"]
o["novel_rgb_evidence"] = rgb
o["parameters"] = params
o["geometry"] = mapping(fitted)
o["observation_geometry"] = mapping(support)
o["fit"] = metrics
o["novel_unbuffered_support"] = immediate
o["context_admission"] = dict(
method=reason,
seed_ids=sorted(set(crossing or supporting or junction)),
candidate_id=original["id"],
seeds_frozen=True,
)
o["id"] = (
"object-"
+ digest(["contextual-strip-v1", original["id"], params, o["context_admission"]])[
:24
]
)
o["kind"] = "crosswalk_bar" if crossing else "linear_marking"
additions.append(o)
accepted.append(o["id"])
occupied = unary_union([occupied, fitted])
decisions.append(
dict(id=original["id"], accepted=bool(accepted), reason=reason, additions=accepted)
)
return additions, decisions