Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
151 lines
5.8 KiB
Python
151 lines
5.8 KiB
Python
"""One image embedding per exact survey window, shared across class requests.
|
|
|
|
A source view, crop, resize, opacity gate and threshold define a request. Only
|
|
identical requests share inference. Consumers retain their own raster assembly.
|
|
No final map, fitted object or scene identity participates in this schedule.
|
|
"""
|
|
|
|
from dataclasses import dataclass, field
|
|
|
|
import cv2
|
|
import numpy as np
|
|
from ortho_windows import merge_instances, windows
|
|
from PIL import Image
|
|
|
|
|
|
@dataclass
|
|
class Request:
|
|
kind: str
|
|
raster_box: tuple
|
|
image_box: tuple
|
|
prompts: list = field(default_factory=list)
|
|
consumers: list = field(default_factory=list)
|
|
|
|
|
|
def schedule(method, alphas, sizes):
|
|
"""Union exact legacy schedules without equating different scale policies."""
|
|
jobs = [
|
|
("coarse", "context", 60, 60, method["prompts"]),
|
|
(
|
|
"medium",
|
|
"context",
|
|
method["context_width_m"],
|
|
method["context_step_m"],
|
|
method["prompts"],
|
|
),
|
|
("detail", "ground", method["detail_width_m"], method["detail_step_m"], method["prompts"]),
|
|
("building", "context", 30, 20, ["building"]),
|
|
("markings", "ground", 15, 10, ["road marking", "crosswalk"]),
|
|
]
|
|
requests = {}
|
|
counts = {}
|
|
for consumer, kind, width, step, prompts in jobs:
|
|
counts[consumer] = dict(accepted=0, skipped=0)
|
|
alpha = alphas[kind]
|
|
if alpha.shape != (1200, 1200):
|
|
raise ValueError("Expected calibrated 1200-pixel opacity")
|
|
for x, y, w, h in windows(60, width, step):
|
|
box = tuple(np.rint(np.array([x, y, x + w, y + h]) * 20).astype(int))
|
|
x0, y0, x1, y1 = box
|
|
if (alpha[y0:y1, x0:x1] > 0.7).mean() < 0.04:
|
|
counts[consumer]["skipped"] += 1
|
|
continue
|
|
counts[consumer]["accepted"] += 1
|
|
image_box = tuple(
|
|
np.rint(np.array([x, y, x + w, y + h]) * sizes[kind] / 60).astype(int)
|
|
)
|
|
key = (kind, box, image_box)
|
|
req = requests.setdefault(key, Request(kind, box, image_box))
|
|
req.consumers.append((consumer, tuple(prompts)))
|
|
for prompt in prompts:
|
|
if prompt not in req.prompts:
|
|
req.prompts.append(prompt)
|
|
return list(requests.values()), counts
|
|
|
|
|
|
def predict_planes(processor, image, prompts):
|
|
"""Same concepts and masks, decoded in bounded batches on one embedding."""
|
|
from batched_concepts import ConceptDecoder
|
|
if not hasattr(processor, '_concept_decoder'):
|
|
processor._concept_decoder = ConceptDecoder(processor, batch_size=3)
|
|
predictions = processor._concept_decoder(image, prompts)
|
|
result = {}
|
|
for prompt in prompts:
|
|
plane = np.zeros((image.height, image.width), np.float32)
|
|
for mask, score in zip(predictions[prompt]['masks'], predictions[prompt]['scores'], strict=True):
|
|
np.maximum(plane, np.where(mask, score, 0), out=plane)
|
|
result[prompt] = plane
|
|
return result
|
|
|
|
|
|
def infer_tile(method, images, alphas, predict):
|
|
if method["prompts"] != ["road", "sidewalk", "vehicle"] or method["model_threshold"] != 0.3:
|
|
raise ValueError("Joint survey requires the qualified common prompt/threshold contract")
|
|
if any(im.width != im.height for im in images.values()):
|
|
raise ValueError("Expected square orthographic observation")
|
|
requests, counts = schedule(method, alphas, {k: im.width for k, im in images.items()})
|
|
canvases = {}
|
|
for req in requests:
|
|
x0, y0, x1, y1 = req.raster_box
|
|
with images[req.kind].crop(req.image_box) as crop:
|
|
crop.thumbnail((1024, 1024), Image.Resampling.LANCZOS)
|
|
planes = predict(crop, req.prompts)
|
|
scaled = {
|
|
p: cv2.resize(planes[p], (x1 - x0, y1 - y0), interpolation=cv2.INTER_AREA)
|
|
for p in req.prompts
|
|
}
|
|
for consumer, prompts in req.consumers:
|
|
canvas = canvases.setdefault(consumer, {})
|
|
for prompt in prompts:
|
|
if prompt not in canvas:
|
|
canvas[prompt] = np.zeros((1200, 1200), np.float32)
|
|
target = canvas[prompt]
|
|
merge_instances(target, scaled[prompt], x0, y0)
|
|
|
|
# Empty/unknown input is an all-zero observation, not a fabricated class.
|
|
def plane(consumer, prompt):
|
|
value = canvases.get(consumer, {}).get(prompt)
|
|
return np.zeros((1200, 1200), np.float32) if value is None else value
|
|
|
|
context = np.asarray([plane("coarse", p) for p in method["prompts"]])
|
|
medium = np.asarray([plane("medium", p) for p in method["prompts"]])
|
|
detail = np.asarray([plane("detail", p) for p in method["prompts"]])
|
|
normal = np.maximum(context, medium)
|
|
combined = np.maximum(normal, detail)
|
|
combined[2] = normal[2]
|
|
combined[:, ~(np.maximum(alphas["context"], alphas["ground"]) > 0.5)] = 0
|
|
road, sidewalk, vehicle = combined
|
|
normal_out = {
|
|
"roadway": road,
|
|
"sidewalk": sidewalk,
|
|
"vehicle": vehicle,
|
|
"road marking": np.zeros_like(road),
|
|
"crosswalk": np.zeros_like(road),
|
|
}
|
|
ground_out = {
|
|
**normal_out,
|
|
"roadway": detail[0],
|
|
"sidewalk": detail[1],
|
|
"vehicle": np.zeros_like(road),
|
|
}
|
|
layers = {}
|
|
for consumer, kind, prompts in [
|
|
("building", "context", ["building"]),
|
|
("markings", "ground", ["road marking", "crosswalk"]),
|
|
]:
|
|
for prompt in prompts:
|
|
value = plane(consumer, prompt)
|
|
value[alphas[kind] < 0.5] = 0
|
|
layers[prompt] = value.astype("float16")
|
|
return (
|
|
normal_out,
|
|
ground_out,
|
|
layers,
|
|
{
|
|
"consumers": counts,
|
|
"image_encodings": len(requests),
|
|
"separate_image_encodings": sum(x["accepted"] for x in counts.values()),
|
|
"prompt_decodes": sum(len(r.prompts) for r in requests),
|
|
},
|
|
)
|