File size: 8,354 Bytes
f877698
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
from __future__ import annotations

import math
import warnings

import numpy as np
from PIL import Image
from scipy.ndimage import binary_fill_holes

RANK_WARNING = getattr(np.exceptions, "RankWarning", None) or np.RankWarning
ROLE_OF_CATEGORY = {"dashboard": "dashboard", "hood": "hood", "pillar": "pillar"}
PANEL_ROLES = frozenset({"dashboard", "hood"})
DEFAULT_PANEL_EDGE = {"degree": 3, "ransac_iters": 500, "inlier_tau_frac": 0.01,
                      "min_support_frac": 0.5, "min_inlier_frac": 0.6, "max_mad_frac": 0.02, "seed": 0}


def panel_edge_settings(params: dict | None) -> dict:
    merged = {**DEFAULT_PANEL_EDGE, **(params or {})}
    if set(merged) != set(DEFAULT_PANEL_EDGE):
        raise ValueError("unknown panel_edge parameter")
    return merged


def repair_entities(masks: np.ndarray, roles: list[str], *, bottom_ratio: float) -> dict[str, np.ndarray]:
    height, width = masks.shape[1:]
    bottom = np.zeros((height, width), bool)
    rows = math.ceil(height * bottom_ratio)
    if rows:
        bottom[-rows:] = True
    filled = []
    for mask, role in zip(masks.astype(bool), roles):
        repaired = binary_fill_holes(mask)
        if role in {"dashboard", "hood"}:
            panel = repaired | bottom
            repaired = binary_fill_holes(panel)
        filled.append(repaired)
    entities = np.stack(filled) if filled else np.zeros(masks.shape, bool)
    occluder = np.any(entities, axis=0) | bottom
    return {"entities": entities.astype(np.uint8), "mask": occluder.astype(np.uint8), "bottom": bottom.astype(np.uint8)}


def extract_panel_edge(masks: np.ndarray, roles: list[str]) -> np.ndarray:
    height, width = masks.shape[1:]
    members = [index for index, role in enumerate(roles) if role in PANEL_ROLES]
    panel = np.any(masks[members].astype(bool), axis=0) if members else np.zeros((height, width), bool)
    present = panel.any(axis=0)
    top = np.full(width, np.nan)
    top[present] = panel.argmax(axis=0)[present]
    return top


def _polyfit(x: np.ndarray, y: np.ndarray, degree: int, w: np.ndarray | None = None) -> np.ndarray:
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", RANK_WARNING)
        return np.polyfit(x, y, degree, w=w)


def fit_panel_edge(top: np.ndarray, size: tuple[int, int], settings: dict) -> dict:
    width, height = size
    settings = panel_edge_settings(settings)
    degree, tau = settings["degree"], settings["inlier_tau_frac"]
    x_all = (np.arange(width) + 0.5) / width
    valid = np.isfinite(top)
    support_frac = float(valid.mean())
    info = {"settings": settings, "size": [width, height],
            "support_frac": support_frac, "supported_columns": int(valid.sum()), "fitted": False, "reasons": []}
    if valid.sum() < degree + 2:
        info["reasons"].append("insufficient supported columns for the polynomial degree")
        return info
    x, y = x_all[valid], top[valid] / height
    rng = np.random.default_rng(settings["seed"])
    best_coeffs, best_inliers, best_score = None, None, (-1, np.inf)
    for _ in range(settings["ransac_iters"]):
        sample = rng.choice(len(x), degree + 1, replace=False)
        if len(np.unique(x[sample])) < degree + 1:
            continue
        coeffs = _polyfit(x[sample], y[sample], degree)
        residual = np.abs(np.polyval(coeffs, x) - y)
        inliers = residual <= tau
        score = (int(inliers.sum()), float(np.median(residual[inliers])) if inliers.any() else np.inf)
        if score[0] > best_score[0] or (score[0] == best_score[0] and score[1] < best_score[1]):
            best_coeffs, best_inliers, best_score = coeffs, inliers, score
    if best_coeffs is None or best_inliers.sum() < degree + 2:
        info["reasons"].append("RANSAC found no consensus set")
        return info
    coeffs = _polyfit(x[best_inliers], y[best_inliers], degree)
    for _ in range(5):
        residual = np.polyval(coeffs, x[best_inliers]) - y[best_inliers]
        scale = max(1.4826 * float(np.median(np.abs(residual))), 1e-6)
        ratio = np.abs(residual) / (1.345 * scale)
        weights = np.where(ratio <= 1, 1.0, 1.0 / np.maximum(ratio, 1e-12))
        coeffs = _polyfit(x[best_inliers], y[best_inliers], degree, w=np.sqrt(weights))
    residual = np.abs(np.polyval(coeffs, x) - y)
    inliers = residual <= tau
    inlier_frac = float(inliers.mean())
    mad = float(np.median(residual[inliers])) if inliers.any() else float("inf")
    clamp_frac = max(0.0, float(np.min(y[inliers])) - tau) if inliers.any() else 0.0
    info.update(degree=degree, coefficients=[float(c) for c in coeffs], inlier_frac=inlier_frac,
                inlier_columns=int(inliers.sum()), residual_mad_frac=mad, clamp_frac=clamp_frac)
    if support_frac < settings["min_support_frac"]:
        info["reasons"].append(f"support_frac {support_frac:.3f} < {settings['min_support_frac']}")
    if inlier_frac < settings["min_inlier_frac"]:
        info["reasons"].append(f"inlier_frac {inlier_frac:.3f} < {settings['min_inlier_frac']}")
    if mad > settings["max_mad_frac"]:
        info["reasons"].append(f"residual_mad_frac {mad:.4f} > {settings['max_mad_frac']}")
    info["fitted"] = not info["reasons"]
    return info


def edge_rows(info: dict, size: tuple[int, int]) -> np.ndarray:
    width, height = size
    x = (np.arange(width) + 0.5) / width
    rows = np.polyval(np.asarray(info["coefficients"], float), x) * height
    rows = np.clip(rows, info["clamp_frac"] * height, height)
    return np.rint(rows).astype(int)


def fill_below_edge(rows: np.ndarray, size: tuple[int, int]) -> np.ndarray:
    width, height = size
    return (np.arange(height)[:, None] >= rows[None, :]).astype(np.uint8)


def repair_entities_edge(masks: np.ndarray, roles: list[str], *, bottom_ratio: float,
                         edge_settings: dict, edge: dict | None = None) -> dict:
    base = repair_entities(masks, roles, bottom_ratio=bottom_ratio)
    height, width = masks.shape[1:]
    if edge is None:
        edge = fit_panel_edge(extract_panel_edge(masks, roles), (width, height), edge_settings)
    if edge.get("fitted"):
        below = fill_below_edge(edge_rows(edge, (width, height)), (width, height)).astype(bool)
        added = below & ~base["mask"].astype(bool)
    else:
        added = np.zeros((height, width), bool)
    occluder = base["mask"].astype(bool) | added
    return {**base, "mask": occluder.astype(np.uint8), "edge": added.astype(np.uint8), "edge_info": edge}


def grid_masks(source: dict, roles: list[str], size: tuple[int, int], *, bottom_ratio: float, edge_settings: dict) -> dict:
    width, height = size
    mapped = [np.asarray(Image.fromarray(mask).resize(size, Image.Resampling.NEAREST), np.uint8) for mask in source["entities"]]
    masks = np.stack(mapped) if mapped else np.zeros((0, height, width), np.uint8)
    return repair_entities_edge(masks, roles, bottom_ratio=bottom_ratio, edge_settings=edge_settings, edge=source["edge_info"])


def assemble_entities(raw: np.ndarray, kept: list[dict], verdict_of: dict[int, dict], post: dict) -> dict:
    yes = [d for d in kept if verdict_of[d["candidate_id"]]["opaque_hard"] == "yes"]
    roles = [ROLE_OF_CATEGORY.get(verdict_of[d["candidate_id"]]["category"], "object") for d in yes]
    height, width = raw.shape[1:]
    masks = raw[[d["index"] for d in yes]] if yes else np.zeros((0, height, width), np.uint8)
    repaired = repair_entities_edge(masks, roles, bottom_ratio=post["bottom_opaque_ratio"], edge_settings=post["panel_edge"])
    entities = [{"candidate_id": d["candidate_id"], "phrase": d["phrase"], "score": d["score"], "role": role,
                 "category": verdict_of[d["candidate_id"]]["category"]} for d, role in zip(yes, roles)]
    summary = {"yes": len(yes), "no": sum(1 for d in kept if verdict_of[d["candidate_id"]]["opaque_hard"] == "no"),
               "uncertain": sorted(d["candidate_id"] for d in kept if verdict_of[d["candidate_id"]]["opaque_hard"] == "uncertain"),
               "roles": {r: roles.count(r) for r in sorted(set(roles))},
               "edge_fitted": bool(repaired["edge_info"].get("fitted")), "edge_reasons": repaired["edge_info"].get("reasons", []),
               "mask_fraction": round(float(repaired["mask"].mean()), 4)}
    return {"masks": masks, "roles": roles, "entities": entities, "repaired": repaired, "summary": summary}