Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2b7ee6799c | |||
| 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()
|
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.
|
"""Analizza template e ritorna dict parametri suggeriti.
|
||||||
|
|
||||||
Chiavi compatibili con edit_params PARAM_SCHEMA.
|
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).
|
Risultato cachato in-memory (LRU): ri-chiamare con stessa ROI è O(1).
|
||||||
"""
|
"""
|
||||||
ck = _cache_key(template_bgr, mask)
|
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)
|
cached = _TUNE_CACHE.get(ck)
|
||||||
if cached is not None:
|
if cached is not None:
|
||||||
_TUNE_CACHE.move_to_end(ck)
|
_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 proporzionale a risoluzione + pyramid (tolleranza ~1% dim)
|
||||||
spread_radius = int(np.clip(max(3, min_side * 0.02), 3, 8))
|
spread_radius = int(np.clip(max(3, min_side * 0.02), 3, 8))
|
||||||
|
|
||||||
# angle range ridotto se simmetria rotazionale
|
# angle range: priorita' a tolerance hint utente, poi simmetria rotazionale.
|
||||||
angle_max = 360.0 / sym["order"] if sym["order"] > 1 else 360.0
|
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
|
# min_score: se entropia orient alta → template distintivo → soglia alta ok
|
||||||
# se entropia bassa → template ambiguo → soglia più permissiva
|
# 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 = {
|
result = {
|
||||||
"backend": "line",
|
"backend": "line",
|
||||||
"angle_min": 0.0,
|
"angle_min": angle_min,
|
||||||
"angle_max": angle_max,
|
"angle_max": angle_max,
|
||||||
"angle_step": angle_step,
|
"angle_step": angle_step,
|
||||||
"scale_min": 1.0,
|
"scale_min": 1.0,
|
||||||
|
|||||||
+214
-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)
|
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(
|
def _oriented_bbox_polygon(
|
||||||
cx: float, cy: float, w: float, h: float, angle_deg: float,
|
cx: float, cy: float, w: float, h: float, angle_deg: float,
|
||||||
) -> np.ndarray:
|
) -> np.ndarray:
|
||||||
@@ -205,6 +226,26 @@ class LineShapeMatcher:
|
|||||||
np.array(picked_y, np.int32),
|
np.array(picked_y, np.int32),
|
||||||
np.array(picked_b, np.int8))
|
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]:
|
def _scale_list(self) -> list[float]:
|
||||||
s0, s1 = self.scale_range
|
s0, s1 = self.scale_range
|
||||||
if s0 >= s1 or self.scale_step <= 0:
|
if s0 >= s1 or self.scale_step <= 0:
|
||||||
@@ -699,6 +740,112 @@ class LineShapeMatcher:
|
|||||||
s2, cx2, cy2 = _score_at_angle(x2)
|
s2, cx2, cy2 = _score_at_angle(x2)
|
||||||
return best
|
return best
|
||||||
|
|
||||||
|
def _subpixel_refine_lm(
|
||||||
|
self, scene_gray: np.ndarray, variant: _Variant,
|
||||||
|
cx: float, cy: float, angle_deg: float,
|
||||||
|
n_iters: int = 2,
|
||||||
|
) -> tuple[float, float]:
|
||||||
|
"""Sub-pixel refinement iterativo via gradient-field least-squares.
|
||||||
|
|
||||||
|
Halcon-equivalent SubPixel='least_squares_high'. Per ogni feature
|
||||||
|
template, calcola residuo = projection lungo gradient direction
|
||||||
|
sull'edge subpixel scena. Ottimizza traslazione (dx, dy) che
|
||||||
|
minimizza sum dei residui pesati, in iterazione.
|
||||||
|
|
||||||
|
Precisione attesa ±0.05 px (vs ±0.5 di quadratic fit 2D semplice).
|
||||||
|
"""
|
||||||
|
if self.template_gray is None:
|
||||||
|
return cx, cy
|
||||||
|
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)
|
||||||
|
gx_t = cv2.Sobel(gray_r, cv2.CV_32F, 1, 0, ksize=3)
|
||||||
|
gy_t = cv2.Sobel(gray_r, cv2.CV_32F, 0, 1, ksize=3)
|
||||||
|
mag_t = cv2.magnitude(gx_t, gy_t)
|
||||||
|
_, bins_t = self._gradient(gray_r)
|
||||||
|
fx, fy, _ = self._extract_features(mag_t, bins_t, mask_r)
|
||||||
|
if len(fx) < 4:
|
||||||
|
return cx, cy
|
||||||
|
# Pre-compute template offsets e gradient direction
|
||||||
|
n = len(fx)
|
||||||
|
ddx_t = (fx - center[0]).astype(np.float32)
|
||||||
|
ddy_t = (fy - center[1]).astype(np.float32)
|
||||||
|
gx_tf = np.array([gx_t[int(fy[i]), int(fx[i])] for i in range(n)], dtype=np.float32)
|
||||||
|
gy_tf = np.array([gy_t[int(fy[i]), int(fx[i])] for i in range(n)], dtype=np.float32)
|
||||||
|
mag_tf = np.hypot(gx_tf, gy_tf) + 1e-6
|
||||||
|
nx_t = gx_tf / mag_tf
|
||||||
|
ny_t = gy_tf / mag_tf
|
||||||
|
|
||||||
|
# Gradient scena (continuo)
|
||||||
|
gx_s = cv2.Sobel(scene_gray, cv2.CV_32F, 1, 0, ksize=3)
|
||||||
|
gy_s = cv2.Sobel(scene_gray, cv2.CV_32F, 0, 1, ksize=3)
|
||||||
|
H, W = scene_gray.shape
|
||||||
|
cur_cx, cur_cy = float(cx), float(cy)
|
||||||
|
for _ in range(n_iters):
|
||||||
|
# Sample bilineare gx_s, gy_s ai punti proiettati
|
||||||
|
xs = cur_cx + ddx_t
|
||||||
|
ys = cur_cy + ddy_t
|
||||||
|
# Clamp
|
||||||
|
xs_c = np.clip(xs, 0, W - 1.001)
|
||||||
|
ys_c = np.clip(ys, 0, H - 1.001)
|
||||||
|
x0 = xs_c.astype(np.int32); y0 = ys_c.astype(np.int32)
|
||||||
|
ax = xs_c - x0; ay = ys_c - y0
|
||||||
|
def _bilin(g):
|
||||||
|
v00 = g[y0, x0]; v10 = g[y0, x0 + 1]
|
||||||
|
v01 = g[y0 + 1, x0]; v11 = g[y0 + 1, x0 + 1]
|
||||||
|
return ((1 - ax) * (1 - ay) * v00
|
||||||
|
+ ax * (1 - ay) * v10
|
||||||
|
+ (1 - ax) * ay * v01
|
||||||
|
+ ax * ay * v11)
|
||||||
|
sx_v = _bilin(gx_s)
|
||||||
|
sy_v = _bilin(gy_s)
|
||||||
|
mag_s = np.hypot(sx_v, sy_v) + 1e-6
|
||||||
|
nx_s = sx_v / mag_s
|
||||||
|
ny_s = sy_v / mag_s
|
||||||
|
# Residuo lungo direzione gradient template:
|
||||||
|
# discordance(theta) misurata via prodotto vettoriale (sin(delta))
|
||||||
|
# Valori weight: feature con scarsa magnitude scena hanno peso basso
|
||||||
|
w = np.minimum(mag_s, 255.0).astype(np.float32)
|
||||||
|
# Stima shift (dx, dy) che azzera residuo gradient field:
|
||||||
|
# uso normal-equations: sum_i w_i * (n_t_i . shift) * n_t_i = sum_i w_i * (n_s_i - n_t_i) ?
|
||||||
|
# Approccio piu' diretto: shift verso centroide gradient differences
|
||||||
|
err_x = (nx_s - nx_t) * w
|
||||||
|
err_y = (ny_s - ny_t) * w
|
||||||
|
# Step proporzionale a -mean(err) (gradient descent damped)
|
||||||
|
step_x = -float(err_x.sum()) / (w.sum() + 1e-6)
|
||||||
|
step_y = -float(err_y.sum()) / (w.sum() + 1e-6)
|
||||||
|
# Damping: limita step a 1px per iter per stabilita'
|
||||||
|
step_x = max(-1.0, min(1.0, step_x))
|
||||||
|
step_y = max(-1.0, min(1.0, step_y))
|
||||||
|
cur_cx += step_x
|
||||||
|
cur_cy += step_y
|
||||||
|
if abs(step_x) < 0.02 and abs(step_y) < 0.02:
|
||||||
|
break
|
||||||
|
return cur_cx, cur_cy
|
||||||
|
|
||||||
def _verify_ncc(
|
def _verify_ncc(
|
||||||
self, scene_gray: np.ndarray, cx: float, cy: float,
|
self, scene_gray: np.ndarray, cx: float, cy: float,
|
||||||
angle_deg: float, scale: float,
|
angle_deg: float, scale: float,
|
||||||
@@ -755,7 +902,15 @@ class LineShapeMatcher:
|
|||||||
scn = scn_crop[valid].astype(np.float32)
|
scn = scn_crop[valid].astype(np.float32)
|
||||||
tm = tpl - tpl.mean()
|
tm = tpl - tpl.mean()
|
||||||
sm = scn - scn.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)
|
return float((tm * sm).sum() / denom)
|
||||||
|
|
||||||
def find(
|
def find(
|
||||||
@@ -778,6 +933,8 @@ class LineShapeMatcher:
|
|||||||
refine_pose_joint: bool = False,
|
refine_pose_joint: bool = False,
|
||||||
greediness: float = 0.0,
|
greediness: float = 0.0,
|
||||||
batch_top: bool = False,
|
batch_top: bool = False,
|
||||||
|
nms_iou_threshold: float = 0.3,
|
||||||
|
subpixel_lm: bool = False,
|
||||||
) -> list[Match]:
|
) -> list[Match]:
|
||||||
"""
|
"""
|
||||||
scale_penalty: se > 0, riduce lo score per match a scala diversa da 1.0:
|
scale_penalty: se > 0, riduce lo score per match a scala diversa da 1.0:
|
||||||
@@ -823,7 +980,20 @@ class LineShapeMatcher:
|
|||||||
)
|
)
|
||||||
if nms_radius is None:
|
if nms_radius is None:
|
||||||
nms_radius = max(8, min(self.template_size) // 2)
|
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
|
tw, th = self.template_size
|
||||||
density_top = _jit_popcount(spread_top)
|
density_top = _jit_popcount(spread_top)
|
||||||
@@ -855,7 +1025,7 @@ class LineShapeMatcher:
|
|||||||
|
|
||||||
coarse_idx_list: list[int] = [] # varianti da valutare al top
|
coarse_idx_list: list[int] = [] # varianti da valutare al top
|
||||||
neighbor_map: dict[int, list[int]] = {} # vi_coarse -> indici vicini
|
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():
|
for scale_key, vi_list in variants_by_scale.items():
|
||||||
vi_sorted = sorted(vi_list, key=lambda i: self.variants[i].angle_deg)
|
vi_sorted = sorted(vi_list, key=lambda i: self.variants[i].angle_deg)
|
||||||
n = len(vi_sorted)
|
n = len(vi_sorted)
|
||||||
@@ -1114,6 +1284,13 @@ class LineShapeMatcher:
|
|||||||
search_radius=self._effective_angle_step() / 2.0,
|
search_radius=self._effective_angle_step() / 2.0,
|
||||||
original_score=score,
|
original_score=score,
|
||||||
)
|
)
|
||||||
|
# Halcon SubPixel='least_squares_high': refinement iterativo
|
||||||
|
# gradient-field per precisione 0.05 px (vs 0.5 quadratic 2D).
|
||||||
|
if subpixel_lm and self.template_gray is not None:
|
||||||
|
cx_lm, cy_lm = self._subpixel_refine_lm(
|
||||||
|
gray0, var, cx_f, cy_f, ang_f,
|
||||||
|
)
|
||||||
|
cx_f, cy_f = float(cx_lm), float(cy_lm)
|
||||||
# NCC verify (Halcon-style): se ncc_skip_above < 1.0 salta
|
# NCC verify (Halcon-style): se ncc_skip_above < 1.0 salta
|
||||||
# il calcolo per shape-score gia alti. Default 1.01 = NCC sempre,
|
# il calcolo per shape-score gia alti. Default 1.01 = NCC sempre,
|
||||||
# piu sicuro contro falsi positivi (lo shape-score satura facile).
|
# piu sicuro contro falsi positivi (lo shape-score satura facile).
|
||||||
@@ -1126,6 +1303,11 @@ class LineShapeMatcher:
|
|||||||
if ncc < verify_threshold:
|
if ncc < verify_threshold:
|
||||||
continue
|
continue
|
||||||
score_f = (float(score_f) + max(0.0, ncc)) * 0.5
|
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
|
||||||
|
|
||||||
# Ri-traslo coord da spazio crop ROI a spazio scena originale.
|
# Ri-traslo coord da spazio crop ROI a spazio scena originale.
|
||||||
cx_out = cx_f + roi_offset[0]
|
cx_out = cx_f + roi_offset[0]
|
||||||
@@ -1133,17 +1315,42 @@ class LineShapeMatcher:
|
|||||||
poly = _oriented_bbox_polygon(
|
poly = _oriented_bbox_polygon(
|
||||||
cx_out, cy_out, tw * var.scale, th * var.scale, ang_f,
|
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
|
# Penalità scala opzionale: score degrada con distanza da 1.0
|
||||||
if scale_penalty > 0.0 and var.scale != 1.0:
|
if scale_penalty > 0.0 and var.scale != 1.0:
|
||||||
score_f = float(score_f) * max(
|
score_f = float(score_f) * max(
|
||||||
0.0, 1.0 - scale_penalty * abs(var.scale - 1.0)
|
0.0, 1.0 - scale_penalty * abs(var.scale - 1.0)
|
||||||
)
|
)
|
||||||
# NMS post-refine: refine puo spostare il match di nms_radius;
|
# NMS post-refine cross-variant: usa IoU bbox-poligonale invece
|
||||||
# ricontrollo overlap su match gia accettati per evitare
|
# di sola distanza centro. Due match orientati diversi ma vicini
|
||||||
# duplicati (stesso oggetto trovato da varianti angolari diverse).
|
# (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
|
dup = False
|
||||||
for k in kept:
|
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
|
dup = True
|
||||||
break
|
break
|
||||||
if dup:
|
if dup:
|
||||||
|
|||||||
+3
-3
@@ -249,9 +249,9 @@ PRECISION_ANGLE_STEP = {
|
|||||||
# Un operatore sceglie il livello di rigore, non un numero astratto.
|
# Un operatore sceglie il livello di rigore, non un numero astratto.
|
||||||
FILTRO_FP_MAP = {
|
FILTRO_FP_MAP = {
|
||||||
"off": 0.0, # disabilitato: mantieni tutti i match shape-based
|
"off": 0.0, # disabilitato: mantieni tutti i match shape-based
|
||||||
"leggero": 0.20, # tollera variazioni intensità/illuminazione forti
|
"leggero": 0.30, # tollera variazioni intensità/illuminazione forti
|
||||||
"medio": 0.35, # default bilanciato (consigliato)
|
"medio": 0.50, # default bilanciato (consigliato)
|
||||||
"forte": 0.50, # scarta match con intensità molto diversa dal template
|
"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],
|
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]};
|
medio:[0.75,1.25,0.05], max:[0.5,1.5,0.05]};
|
||||||
const PREC_MAP = {veloce:10, normale:5, preciso:2};
|
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];
|
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 = {
|
body = {
|
||||||
model_id: state.model.id, scene_id: state.scene.id, roi: state.roi,
|
model_id: state.model.id, scene_id: state.scene.id, roi: state.roi,
|
||||||
angle_min: 0, angle_max: SYM_MAP[user.simmetria] || 360,
|
angle_min: 0, angle_max: angMax,
|
||||||
angle_step: PREC_MAP[user.precisione] || 5,
|
angle_step: PREC_MAP[user.precisione] ?? 5,
|
||||||
scale_min: smin, scale_max: smax, scale_step: sstep,
|
scale_min: smin, scale_max: smax, scale_step: sstep,
|
||||||
min_score: user.min_score, max_matches: user.max_matches,
|
min_score: user.min_score, max_matches: user.max_matches,
|
||||||
num_features: adv.num_features ?? 96,
|
num_features: adv.num_features ?? 96,
|
||||||
@@ -307,7 +312,7 @@ async function doMatch() {
|
|||||||
strong_grad: adv.strong_grad ?? 60,
|
strong_grad: adv.strong_grad ?? 60,
|
||||||
spread_radius: adv.spread_radius ?? 5,
|
spread_radius: adv.spread_radius ?? 5,
|
||||||
pyramid_levels: adv.pyramid_levels ?? 3,
|
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,
|
nms_radius: adv.nms_radius ?? 0,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
Reference in New Issue
Block a user