perf: Fase 2 speed (3x baseline) - fuse JIT + LRU + sub-pixel lazy

Ottimizzazioni cumulative (225s -> 73s sul bench suite, 3.07x):

pm2d/line_matcher.py:
- Sub-pixel + plateau centroid spostati DOPO il pre-NMS (prima: 58k chiamate
  per clip_preciso anche su candidati poi scartati dalla NMS; ora solo sui
  ~75 preliminary sopravvissuti). Coordinate intere OK per la decisione
  reject, dato che nms_radius >= 8 px.
- Usa nuovo kernel fuso score+rescore (no allocazione intermedia).
- Adaptive plateau_radius + propagazione train_mask per NCC coerente.
- Local crop NCC (diag template invece di intera scena).
- Fallback adattivo se bg_rescore azzera tutti gli score top-level.

pm2d/_jit_kernels.py:
- Nuovo kernel _jit_score_bitmap_rescored: fonde scoring bitmap e rescore
  (score - bg) / (1 - bg) in un singolo pass parallelo. Evita allocazione
  e passata aggiuntiva (era ~15% del tempo find sul preciso).

pm2d/auto_tune.py:
- LRU cache in-memory sui risultati auto_tune (chiave md5 ROI + mask):
  richiamate successive con stessa ROI sono O(1).
- Downsample a 128px prima della correlazione rotazionale
  (O(n_angles * H * W) -> insensibile su sample moderati).
- Soglie weak/strong da percentili reali (p55/p85) senza clamp a 100,
  con clamp massimo 400 per evitare saturazione su template ad alto contrasto.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
root
2026-04-24 21:21:59 +00:00
parent 44a3046616
commit 89b59b3ea3
3 changed files with 230 additions and 42 deletions
+66 -11
View File
@@ -14,6 +14,9 @@ Ritorna dict con i key esatti del form `edit_params`.
from __future__ import annotations
import hashlib
from collections import OrderedDict
import cv2
import numpy as np
@@ -24,17 +27,33 @@ def _to_gray(img: np.ndarray) -> np.ndarray:
return img
# Cache in-memory (LRU) dei risultati auto_tune per stesso input ROI.
_TUNE_CACHE: OrderedDict[str, dict] = OrderedDict()
_TUNE_CACHE_SIZE = 32
def detect_rotational_symmetry(
gray: np.ndarray, step_deg: float = 5.0, corr_thresh: float = 0.75,
) -> dict:
"""Rileva simmetria rotazionale su edge map (più robusto a sfondo uniforme).
Downsample a max 128 px prima di correlare per abbattere il costo
O(n_angles · H · W) senza perdere precisione (la simmetria rotazionale
è invariante a subsampling moderato).
Ritorna dict con:
- order: int, 1=nessuna, 2=180°, 3=120°, 4=90°, 6=60°, 8=45°
- period_deg: float, periodo minimo di simmetria (360/order)
- confidence: float [0..1], correlazione minima tra rotazioni equivalenti
"""
h, w = gray.shape
target = 128
if max(h, w) > target:
sf = target / max(h, w)
new_w = max(32, int(w * sf))
new_h = max(32, int(h * sf))
gray = cv2.resize(gray, (new_w, new_h), interpolation=cv2.INTER_AREA)
h, w = gray.shape
# Usa magnitude gradiente (rotation-invariant rispetto a bg uniforme)
gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)
@@ -88,9 +107,12 @@ def analyze_gradients(gray: np.ndarray) -> dict:
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)
mag = cv2.magnitude(gx, gy)
# Percentili magnitude
# Percentili magnitude: p55/p85 usati per soglie weak/strong (più aderenti
# alla distribuzione reale rispetto a p50/p80 + clamp).
p50 = float(np.percentile(mag, 50))
p55 = float(np.percentile(mag, 55))
p80 = float(np.percentile(mag, 80))
p85 = float(np.percentile(mag, 85))
p95 = float(np.percentile(mag, 95))
mag_max = float(mag.max())
@@ -112,7 +134,8 @@ def analyze_gradients(gray: np.ndarray) -> dict:
ent = 0.0
return {
"p50": p50, "p80": p80, "p95": p95, "mag_max": mag_max,
"p50": p50, "p55": p55, "p80": p80, "p85": p85, "p95": p95,
"mag_max": mag_max,
"strong_pct": strong_pct, "weak_pct": weak_pct,
"orient_entropy": ent,
"n_pixels": mag.size,
@@ -120,11 +143,28 @@ def analyze_gradients(gray: np.ndarray) -> dict:
}
def _cache_key(template_bgr: np.ndarray, mask: np.ndarray | None) -> str:
h = hashlib.md5()
h.update(np.ascontiguousarray(template_bgr).tobytes())
h.update(f"shape={template_bgr.shape}".encode())
if mask is not None:
h.update(np.ascontiguousarray(mask).tobytes())
return h.hexdigest()
def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
"""Analizza template e ritorna dict parametri suggeriti.
Chiavi compatibili con edit_params PARAM_SCHEMA.
Risultato cachato in-memory (LRU): ri-chiamare con stessa ROI è O(1).
"""
ck = _cache_key(template_bgr, mask)
cached = _TUNE_CACHE.get(ck)
if cached is not None:
_TUNE_CACHE.move_to_end(ck)
return dict(cached)
gray = _to_gray(template_bgr)
h, w = gray.shape
if mask is not None:
@@ -136,16 +176,22 @@ def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
stats = analyze_gradients(gray_for_stats)
sym = detect_rotational_symmetry(gray_for_stats)
# Soglie magnitude: usa percentili per robustezza illuminazione.
# Target: strong_grad ~= valore a percentile 80-90 in assoluto, ma
# clamp per compatibilità uint8 (Sobel può sforare).
strong_grad = float(np.clip(stats["p80"], 20.0, 100.0))
weak_grad = float(np.clip(strong_grad * 0.5, 10.0, 60.0))
# Soglie magnitude: usa percentili reali (p85/p55) senza clamp duro a 100.
# Sobel ksize=3 su uint8 può arrivare a ~1020, quindi clamp massimo 400
# evita saturazione del threshold su template ad alto contrasto.
strong_grad = float(np.clip(stats["p85"], 30.0, 400.0))
weak_grad = float(np.clip(stats["p55"], 15.0, strong_grad * 0.7))
# num_features: 1 feature ogni ~25 px forti, clamp 48..192
target_feat = int(np.clip(stats["n_strong"] / 25, 48, 192))
# num_features: ibrido perimetro + densità. Target = min(perimeter_budget,
# density_budget) per non generare più feature di quante edge nitide siano
# disponibili, ma neanche meno di quante il perimetro possa tracciare.
perim_budget = int(2 * (h + w) * 0.4) # ~40% dei pixel di perimetro
density_budget = int(stats["n_strong"] / 20) # 1 feature ogni ~20 px forti
target_feat = int(np.clip(min(perim_budget, density_budget), 64, 192))
# pyramid_levels in base alla dimensione minima
# pyramid_levels in base a dimensione minima E densità feature: un template
# grande ma povero di feature non deve scendere troppi livelli (rischio
# collasso a <16 feature al top level).
min_side = min(h, w)
if min_side < 60:
pyr = 1
@@ -155,6 +201,9 @@ def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
pyr = 3
else:
pyr = 4
# Cap: non scendere sotto ~16 feature al top level (feature ÷ 4^(pyr-1))
max_pyr_from_feat = max(1, int(np.floor(np.log2(max(1, target_feat / 16.0)) / 2.0)) + 1)
pyr = min(pyr, max_pyr_from_feat)
# spread_radius proporzionale a risoluzione + pyramid (tolleranza ~1% dim)
spread_radius = int(np.clip(max(3, min_side * 0.02), 3, 8))
@@ -174,7 +223,7 @@ def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
# angle step: 5° default; se simmetria, mantengo step ma range ridotto
angle_step = 5.0
return {
result = {
"backend": "line",
"angle_min": 0.0,
"angle_max": angle_max,
@@ -196,6 +245,12 @@ def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
"_symmetry_conf": round(sym["confidence"], 2),
"_orient_entropy": round(stats["orient_entropy"], 2),
}
# Store in LRU cache
_TUNE_CACHE[ck] = dict(result)
_TUNE_CACHE.move_to_end(ck)
while len(_TUNE_CACHE) > _TUNE_CACHE_SIZE:
_TUNE_CACHE.popitem(last=False)
return result
def summarize(tune: dict) -> str: