Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f05dec5183 | |||
| f8f6a15166 | |||
| 5bd8fca248 | |||
| 796ccb8052 | |||
| 0a8a9365bb | |||
| 9ed779637e | |||
| 077d44c3c8 | |||
| e038ee3a1d | |||
| 041b26e791 | |||
| 8d8a89ac35 |
+22
-4
@@ -152,14 +152,27 @@ def _cache_key(template_bgr: np.ndarray, mask: np.ndarray | None) -> str:
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
|
||||
def auto_tune(
|
||||
template_bgr: np.ndarray,
|
||||
mask: np.ndarray | None = None,
|
||||
angle_tolerance_deg: float | None = None,
|
||||
angle_center_deg: float = 0.0,
|
||||
) -> dict:
|
||||
"""Analizza template e ritorna dict parametri suggeriti.
|
||||
|
||||
Chiavi compatibili con edit_params PARAM_SCHEMA.
|
||||
|
||||
angle_tolerance_deg: se != None, restringe angle_range a
|
||||
(center - tol, center + tol). Usare quando l'orientamento del
|
||||
pezzo e' noto a priori (feeder con guida, posizionamento
|
||||
meccanico): training molto piu rapido (24x meno varianti per
|
||||
tol=15° vs 360° pieno).
|
||||
|
||||
Risultato cachato in-memory (LRU): ri-chiamare con stessa ROI è O(1).
|
||||
"""
|
||||
ck = _cache_key(template_bgr, mask)
|
||||
if angle_tolerance_deg is not None:
|
||||
ck = f"{ck}|tol={angle_tolerance_deg}|c={angle_center_deg}"
|
||||
cached = _TUNE_CACHE.get(ck)
|
||||
if cached is not None:
|
||||
_TUNE_CACHE.move_to_end(ck)
|
||||
@@ -208,8 +221,13 @@ def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
|
||||
# spread_radius proporzionale a risoluzione + pyramid (tolleranza ~1% dim)
|
||||
spread_radius = int(np.clip(max(3, min_side * 0.02), 3, 8))
|
||||
|
||||
# angle range ridotto se simmetria rotazionale
|
||||
angle_max = 360.0 / sym["order"] if sym["order"] > 1 else 360.0
|
||||
# angle range: priorita' a tolerance hint utente, poi simmetria rotazionale.
|
||||
if angle_tolerance_deg is not None:
|
||||
angle_min = float(angle_center_deg - angle_tolerance_deg)
|
||||
angle_max = float(angle_center_deg + angle_tolerance_deg)
|
||||
else:
|
||||
angle_min = 0.0
|
||||
angle_max = 360.0 / sym["order"] if sym["order"] > 1 else 360.0
|
||||
|
||||
# min_score: se entropia orient alta → template distintivo → soglia alta ok
|
||||
# se entropia bassa → template ambiguo → soglia più permissiva
|
||||
@@ -228,7 +246,7 @@ def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
|
||||
|
||||
result = {
|
||||
"backend": "line",
|
||||
"angle_min": 0.0,
|
||||
"angle_min": angle_min,
|
||||
"angle_max": angle_max,
|
||||
"angle_step": angle_step,
|
||||
"scale_min": 1.0,
|
||||
|
||||
+169
-7
@@ -50,6 +50,27 @@ N_BINS = 8 # default: orientamento mod π (no polarity)
|
||||
N_BINS_POL = 16 # use_polarity=True: orientamento mod 2π (con polarity)
|
||||
|
||||
|
||||
def _poly_iou(p1: np.ndarray, p2: np.ndarray) -> float:
|
||||
"""IoU tra due poligoni convessi (4 vertici, float32) via cv2.intersectConvexConvex.
|
||||
|
||||
Usa OpenCV (cv2.intersectConvexConvex) per intersezione esatta:
|
||||
ritorna area intersezione / area unione. Robusto a rotazioni
|
||||
qualsiasi (anti-orarie/orarie) - cv2 normalizza orientamento.
|
||||
"""
|
||||
a1 = float(cv2.contourArea(p1))
|
||||
a2 = float(cv2.contourArea(p2))
|
||||
if a1 <= 0 or a2 <= 0:
|
||||
return 0.0
|
||||
inter_area, _ = cv2.intersectConvexConvex(
|
||||
p1.astype(np.float32), p2.astype(np.float32),
|
||||
)
|
||||
inter_area = float(inter_area)
|
||||
if inter_area <= 0:
|
||||
return 0.0
|
||||
union = a1 + a2 - inter_area
|
||||
return inter_area / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def _oriented_bbox_polygon(
|
||||
cx: float, cy: float, w: float, h: float, angle_deg: float,
|
||||
) -> np.ndarray:
|
||||
@@ -205,6 +226,26 @@ class LineShapeMatcher:
|
||||
np.array(picked_y, np.int32),
|
||||
np.array(picked_b, np.int8))
|
||||
|
||||
def set_angle_range_around(
|
||||
self, center_deg: float, tolerance_deg: float,
|
||||
) -> None:
|
||||
"""Restringe angle_range a (center - tol, center + tol).
|
||||
|
||||
Comodo helper per scenari in cui l'orientamento del pezzo e'
|
||||
noto a priori entro ±tolerance_deg (es. feeder vibrante con
|
||||
guida meccanica). Riduce drasticamente le varianti generate
|
||||
in train(): es. ±15° vs 360° = 24x meno varianti, training
|
||||
e matching molto piu veloci.
|
||||
|
||||
Esempio:
|
||||
m.set_angle_range_around(0, 20) # cerca solo in [-20, +20]
|
||||
m.train(template)
|
||||
"""
|
||||
self.angle_range_deg = (
|
||||
float(center_deg - tolerance_deg),
|
||||
float(center_deg + tolerance_deg),
|
||||
)
|
||||
|
||||
def _scale_list(self) -> list[float]:
|
||||
s0, s1 = self.scale_range
|
||||
if s0 >= s1 or self.scale_step <= 0:
|
||||
@@ -699,6 +740,63 @@ class LineShapeMatcher:
|
||||
s2, cx2, cy2 = _score_at_angle(x2)
|
||||
return best
|
||||
|
||||
def _compute_recall(
|
||||
self, spread0: np.ndarray, variant: _Variant,
|
||||
cx: float, cy: float, angle_deg: float,
|
||||
) -> float:
|
||||
"""Frazione di feature template che combaciano nello spread scena
|
||||
alla pose (cx, cy, angle, variant.scale).
|
||||
|
||||
Riusa template_gray + warp per estrarre features alla pose esatta
|
||||
(vs feature pre-computate alla pose della variante grezza). Ritorna
|
||||
hits/N in [0, 1]. Halcon-equivalent: questo e' il "MinScore" originale.
|
||||
"""
|
||||
if self.template_gray is None:
|
||||
return 1.0
|
||||
h, w = self.template_gray.shape
|
||||
scale = variant.scale
|
||||
sw = max(16, int(round(w * scale)))
|
||||
sh = max(16, int(round(h * scale)))
|
||||
gray_s = cv2.resize(self.template_gray, (sw, sh), interpolation=cv2.INTER_LINEAR)
|
||||
mask_src = (
|
||||
self._train_mask if self._train_mask is not None
|
||||
else np.full_like(self.template_gray, 255)
|
||||
)
|
||||
mask_s = cv2.resize(mask_src, (sw, sh), interpolation=cv2.INTER_NEAREST)
|
||||
diag = int(np.ceil(np.hypot(sh, sw))) + 6
|
||||
py = (diag - sh) // 2; px = (diag - sw) // 2
|
||||
gray_p = cv2.copyMakeBorder(
|
||||
gray_s, py, diag - sh - py, px, diag - sw - px, cv2.BORDER_REPLICATE,
|
||||
)
|
||||
mask_p = cv2.copyMakeBorder(
|
||||
mask_s, py, diag - sh - py, px, diag - sw - px,
|
||||
cv2.BORDER_CONSTANT, value=0,
|
||||
)
|
||||
center = (diag / 2.0, diag / 2.0)
|
||||
M = cv2.getRotationMatrix2D(center, angle_deg, 1.0)
|
||||
gray_r = cv2.warpAffine(gray_p, M, (diag, diag),
|
||||
flags=cv2.INTER_LINEAR,
|
||||
borderMode=cv2.BORDER_REPLICATE)
|
||||
mask_r = cv2.warpAffine(mask_p, M, (diag, diag),
|
||||
flags=cv2.INTER_NEAREST, borderValue=0)
|
||||
mag, bins = self._gradient(gray_r)
|
||||
fx, fy, fb = self._extract_features(mag, bins, mask_r)
|
||||
n_feat = len(fx)
|
||||
if n_feat < 4:
|
||||
return 0.0
|
||||
H, W = spread0.shape
|
||||
spread_dtype = spread0.dtype.type
|
||||
ix = int(round(cx)); iy = int(round(cy))
|
||||
hits = 0
|
||||
for i in range(n_feat):
|
||||
xs = ix + int(fx[i] - center[0])
|
||||
ys = iy + int(fy[i] - center[1])
|
||||
if 0 <= xs < W and 0 <= ys < H:
|
||||
bit = spread_dtype(1 << int(fb[i]))
|
||||
if spread0[ys, xs] & bit:
|
||||
hits += 1
|
||||
return hits / n_feat
|
||||
|
||||
def _verify_ncc(
|
||||
self, scene_gray: np.ndarray, cx: float, cy: float,
|
||||
angle_deg: float, scale: float,
|
||||
@@ -755,7 +853,15 @@ class LineShapeMatcher:
|
||||
scn = scn_crop[valid].astype(np.float32)
|
||||
tm = tpl - tpl.mean()
|
||||
sm = scn - scn.mean()
|
||||
denom = np.sqrt((tm * tm).sum() * (sm * sm).sum()) + 1e-9
|
||||
# Std minimo: se template o scena patch sono quasi uniformi
|
||||
# (es. zona di sfondo bianco/nero), NCC e instabile e da false
|
||||
# high-correlation. Halcon-style: scarta match.
|
||||
tpl_var = float((tm * tm).sum())
|
||||
scn_var = float((sm * sm).sum())
|
||||
n_pix = float(valid.sum())
|
||||
if tpl_var < 1e-3 * n_pix or scn_var < 1e-3 * n_pix:
|
||||
return 0.0
|
||||
denom = np.sqrt(tpl_var * scn_var) + 1e-9
|
||||
return float((tm * sm).sum() / denom)
|
||||
|
||||
def find(
|
||||
@@ -778,6 +884,8 @@ class LineShapeMatcher:
|
||||
refine_pose_joint: bool = False,
|
||||
greediness: float = 0.0,
|
||||
batch_top: bool = False,
|
||||
nms_iou_threshold: float = 0.3,
|
||||
min_recall: float = 0.0,
|
||||
) -> list[Match]:
|
||||
"""
|
||||
scale_penalty: se > 0, riduce lo score per match a scala diversa da 1.0:
|
||||
@@ -823,7 +931,20 @@ class LineShapeMatcher:
|
||||
)
|
||||
if nms_radius is None:
|
||||
nms_radius = max(8, min(self.template_size) // 2)
|
||||
top_thresh = min_score * self.top_score_factor
|
||||
# Pruning adattivo allo step angolare: con step piccolo (<= 3 deg)
|
||||
# ci sono molte varianti vicine, gli score top-level sono ravvicinati
|
||||
# e top_thresh*0.5 e' troppo aggressivo: scarta varianti valide che
|
||||
# sarebbero state riprese al full-res. Stessa cosa per
|
||||
# coarse_angle_factor (skip 1 ogni 2): con step fine non e' utile.
|
||||
# Risultato osservato: precisione "veloce" 10° dava risultati
|
||||
# migliori di "preciso" 2° proprio perche evitava il pruning.
|
||||
eff_step = self._effective_angle_step()
|
||||
top_factor = self.top_score_factor
|
||||
cf_eff = max(1, coarse_angle_factor)
|
||||
if eff_step <= 3.0:
|
||||
top_factor = max(top_factor, 0.7)
|
||||
cf_eff = 1
|
||||
top_thresh = min_score * top_factor
|
||||
|
||||
tw, th = self.template_size
|
||||
density_top = _jit_popcount(spread_top)
|
||||
@@ -855,7 +976,7 @@ class LineShapeMatcher:
|
||||
|
||||
coarse_idx_list: list[int] = [] # varianti da valutare al top
|
||||
neighbor_map: dict[int, list[int]] = {} # vi_coarse -> indici vicini
|
||||
cf = max(1, coarse_angle_factor)
|
||||
cf = cf_eff
|
||||
for scale_key, vi_list in variants_by_scale.items():
|
||||
vi_sorted = sorted(vi_list, key=lambda i: self.variants[i].angle_deg)
|
||||
n = len(vi_sorted)
|
||||
@@ -1126,6 +1247,22 @@ class LineShapeMatcher:
|
||||
if ncc < verify_threshold:
|
||||
continue
|
||||
score_f = (float(score_f) + max(0.0, ncc)) * 0.5
|
||||
# Re-check min_score sullo score finale: NCC averaging puo
|
||||
# abbattere lo shape-score sotto la soglia user. Senza questo
|
||||
# check apparivano match con score < min_score (UI confusing).
|
||||
if float(score_f) < min_score:
|
||||
continue
|
||||
|
||||
# Feature recall (Halcon MinScore-style): conta quante feature
|
||||
# template effettivamente combaciano nello spread scena alla
|
||||
# pose finale. Scarta se sotto min_recall (default 0 = off).
|
||||
# Util contro match parziali ad alto NCC ma poche feature reali.
|
||||
if min_recall > 0.0:
|
||||
recall = self._compute_recall(
|
||||
spread0, var, cx_f, cy_f, ang_f,
|
||||
)
|
||||
if recall < min_recall:
|
||||
continue
|
||||
|
||||
# Ri-traslo coord da spazio crop ROI a spazio scena originale.
|
||||
cx_out = cx_f + roi_offset[0]
|
||||
@@ -1133,17 +1270,42 @@ class LineShapeMatcher:
|
||||
poly = _oriented_bbox_polygon(
|
||||
cx_out, cy_out, tw * var.scale, th * var.scale, ang_f,
|
||||
)
|
||||
# Reject match con bbox che sfora pesantemente la scena:
|
||||
# spesso indica match spurio (centro derivato male o scala
|
||||
# incoerente). Tollera 25% out-of-bounds, sopra rigetta.
|
||||
H_scn, W_scn = gray_full.shape
|
||||
poly_area = float(cv2.contourArea(poly))
|
||||
if poly_area > 0:
|
||||
# Clip poly alla scena: intersezione con rettangolo (0,0,W,H)
|
||||
scene_rect = np.array([
|
||||
[0, 0], [W_scn, 0], [W_scn, H_scn], [0, H_scn],
|
||||
], dtype=np.float32)
|
||||
inter, _ = cv2.intersectConvexConvex(
|
||||
poly.astype(np.float32), scene_rect,
|
||||
)
|
||||
inside_ratio = float(inter) / poly_area
|
||||
if inside_ratio < 0.75:
|
||||
continue
|
||||
# Penalità scala opzionale: score degrada con distanza da 1.0
|
||||
if scale_penalty > 0.0 and var.scale != 1.0:
|
||||
score_f = float(score_f) * max(
|
||||
0.0, 1.0 - scale_penalty * abs(var.scale - 1.0)
|
||||
)
|
||||
# NMS post-refine: refine puo spostare il match di nms_radius;
|
||||
# ricontrollo overlap su match gia accettati per evitare
|
||||
# duplicati (stesso oggetto trovato da varianti angolari diverse).
|
||||
# NMS post-refine cross-variant: usa IoU bbox-poligonale invece
|
||||
# di sola distanza centro. Due match orientati diversi ma vicini
|
||||
# (pezzi adiacenti) NON vengono fusi se l'overlap reale e basso;
|
||||
# due match dello stesso pezzo (centri uguali, rotazione simile)
|
||||
# hanno IoU alto e vengono droppati.
|
||||
# Fallback distanza centro per match con bbox degenere.
|
||||
dup = False
|
||||
for k in kept:
|
||||
if (k.cx - cx_out) ** 2 + (k.cy - cy_out) ** 2 < r2:
|
||||
iou = _poly_iou(k.bbox_poly, poly)
|
||||
if iou > nms_iou_threshold:
|
||||
dup = True
|
||||
break
|
||||
# Sicurezza: centri molto vicini (dentro nms_radius/2)
|
||||
# sempre fusi, anche con orientamenti molto diversi.
|
||||
if (k.cx - cx_out) ** 2 + (k.cy - cy_out) ** 2 < (r2 / 4.0):
|
||||
dup = True
|
||||
break
|
||||
if dup:
|
||||
|
||||
+3
-3
@@ -249,9 +249,9 @@ PRECISION_ANGLE_STEP = {
|
||||
# Un operatore sceglie il livello di rigore, non un numero astratto.
|
||||
FILTRO_FP_MAP = {
|
||||
"off": 0.0, # disabilitato: mantieni tutti i match shape-based
|
||||
"leggero": 0.20, # tollera variazioni intensità/illuminazione forti
|
||||
"medio": 0.35, # default bilanciato (consigliato)
|
||||
"forte": 0.50, # scarta match con intensità molto diversa dal template
|
||||
"leggero": 0.30, # tollera variazioni intensità/illuminazione forti
|
||||
"medio": 0.50, # default bilanciato (consigliato)
|
||||
"forte": 0.70, # scarta match con intensità molto diversa dal template
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -294,12 +294,17 @@ async function doMatch() {
|
||||
const SCALE_MAP = {fissa:[1,1,0.1], mini:[0.9,1.1,0.05],
|
||||
medio:[0.75,1.25,0.05], max:[0.5,1.5,0.05]};
|
||||
const PREC_MAP = {veloce:10, normale:5, preciso:2};
|
||||
const FP_MAP = {off:0, leggero:0.20, medio:0.35, forte:0.50};
|
||||
// Allineato a FILTRO_FP_MAP server-side (server.py)
|
||||
const FP_MAP = {off:0, leggero:0.30, medio:0.50, forte:0.70};
|
||||
const [smin, smax, sstep] = SCALE_MAP[user.scala];
|
||||
// NB: SYM_MAP[invariante]=0 e' valido (zero rotazioni). Uso ?? per
|
||||
// distinguere "chiave mancante" da "valore zero": altrimenti 0 || 360
|
||||
// collassa invariante a 360 = bug "simmetria non ha effetto".
|
||||
const angMax = SYM_MAP[user.simmetria] ?? 360;
|
||||
body = {
|
||||
model_id: state.model.id, scene_id: state.scene.id, roi: state.roi,
|
||||
angle_min: 0, angle_max: SYM_MAP[user.simmetria] || 360,
|
||||
angle_step: PREC_MAP[user.precisione] || 5,
|
||||
angle_min: 0, angle_max: angMax,
|
||||
angle_step: PREC_MAP[user.precisione] ?? 5,
|
||||
scale_min: smin, scale_max: smax, scale_step: sstep,
|
||||
min_score: user.min_score, max_matches: user.max_matches,
|
||||
num_features: adv.num_features ?? 96,
|
||||
@@ -307,7 +312,7 @@ async function doMatch() {
|
||||
strong_grad: adv.strong_grad ?? 60,
|
||||
spread_radius: adv.spread_radius ?? 5,
|
||||
pyramid_levels: adv.pyramid_levels ?? 3,
|
||||
verify_threshold: adv.verify_threshold ?? (FP_MAP[user.filtro_fp] ?? 0.35),
|
||||
verify_threshold: adv.verify_threshold ?? (FP_MAP[user.filtro_fp] ?? 0.50),
|
||||
nms_radius: adv.nms_radius ?? 0,
|
||||
};
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user