Compare commits
44 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eba9d478a7 | |||
| 0df0d98aa5 | |||
| b2b959e801 | |||
| b05246b492 | |||
| aeaa7fb5f7 | |||
| f347a10fad | |||
| 0b24be4d94 | |||
| 0296083e3c | |||
| 39208aadab | |||
| 2b7ee6799c | |||
| 5059ce1d89 | |||
| f05dec5183 | |||
| f8f6a15166 | |||
| 5bd8fca248 | |||
| 796ccb8052 | |||
| 0a8a9365bb | |||
| 9ed779637e | |||
| 077d44c3c8 | |||
| e038ee3a1d | |||
| 041b26e791 | |||
| 84b73dc651 | |||
| 8d8a89ac35 | |||
| 41976f574d | |||
| 4ef7a4a85f | |||
| 7de7f35b7c | |||
| 7b014b7f69 | |||
| 367ee9aaac | |||
| 74e5a45a39 | |||
| 11c5160385 | |||
| 07bab87cb9 | |||
| a247484f36 | |||
| e188df0adb | |||
| b35d47669c | |||
| fc3b0dbc3a | |||
| 6da4dd5329 | |||
| b143c6607a | |||
| 6704d66cd5 | |||
| 4419c237b2 | |||
| f00cf9b621 | |||
| 746d1668c6 | |||
| d9a40952c4 | |||
| 6db2086ead | |||
| 27a0ef1a45 | |||
| ba4024d252 |
+380
-12
@@ -110,6 +110,118 @@ if HAS_NUMBA:
|
||||
acc[y, x] *= inv
|
||||
return acc
|
||||
|
||||
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||
def _jit_score_bitmap_rescored_strided(
|
||||
spread: np.ndarray,
|
||||
dx: np.ndarray, dy: np.ndarray, bins: np.ndarray,
|
||||
bit_active: np.uint8,
|
||||
bg: np.ndarray,
|
||||
stride: nb.int32,
|
||||
) -> np.ndarray:
|
||||
"""Variante con sub-sampling: valuta solo pixel su griglia stride×stride.
|
||||
Score restituito ha stessa shape (H, W); celle non valutate = 0.
|
||||
|
||||
4× speed-up con stride=2 (NMS recupera precisione in full-res).
|
||||
Numba prange richiede step costante: itero su indici griglia e
|
||||
moltiplico per stride dentro il body.
|
||||
"""
|
||||
H, W = spread.shape
|
||||
N = dx.shape[0]
|
||||
acc = np.zeros((H, W), dtype=np.float32)
|
||||
ny = (H + stride - 1) // stride
|
||||
nx = (W + stride - 1) // stride
|
||||
for yi in nb.prange(ny):
|
||||
y = yi * stride
|
||||
for i in range(N):
|
||||
b = bins[i]
|
||||
mask = np.uint8(1) << b
|
||||
if (bit_active & mask) == 0:
|
||||
continue
|
||||
ddy = dy[i]
|
||||
yy = y + ddy
|
||||
if yy < 0 or yy >= H:
|
||||
continue
|
||||
ddx = dx[i]
|
||||
x_lo = 0 if ddx >= 0 else -ddx
|
||||
x_hi = W if ddx <= 0 else W - ddx
|
||||
rem = x_lo % stride
|
||||
if rem != 0:
|
||||
x_lo += stride - rem
|
||||
x = x_lo
|
||||
while x < x_hi:
|
||||
if spread[yy, x + ddx] & mask:
|
||||
acc[y, x] += 1.0
|
||||
x += stride
|
||||
if N > 0:
|
||||
inv = 1.0 / N
|
||||
for yi in nb.prange(ny):
|
||||
y = yi * stride
|
||||
for xi in range(nx):
|
||||
x = xi * stride
|
||||
v = acc[y, x] * inv
|
||||
bgv = bg[y, x]
|
||||
if bgv < 1.0:
|
||||
r = (v - bgv) / (1.0 - bgv + 1e-6)
|
||||
acc[y, x] = r if r > 0.0 else 0.0
|
||||
else:
|
||||
acc[y, x] = 0.0
|
||||
return acc
|
||||
|
||||
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||
def _jit_score_bitmap_greedy(
|
||||
spread: np.ndarray,
|
||||
dx: np.ndarray, dy: np.ndarray, bins: np.ndarray,
|
||||
bit_active: np.uint8,
|
||||
min_score: nb.float32,
|
||||
greediness: nb.float32,
|
||||
) -> np.ndarray:
|
||||
"""Score bitmap con early-exit greedy (no rescore background).
|
||||
|
||||
Per ogni pixel iteriamo le N feature; abortiamo non appena diventa
|
||||
impossibile raggiungere `min_required` count anche aggiungendo
|
||||
tutte le feature rimanenti. min_required = greediness * min_score * N.
|
||||
|
||||
greediness=0 → nessun early-exit (equivalente a kernel base).
|
||||
greediness=1 → exit non appena hits + remaining < min_score * N.
|
||||
Tipico: 0.7-0.9 → 2-4x speed-up senza perdere match.
|
||||
"""
|
||||
H, W = spread.shape
|
||||
N = dx.shape[0]
|
||||
acc = np.zeros((H, W), dtype=np.float32)
|
||||
if N == 0:
|
||||
return acc
|
||||
min_req = greediness * min_score * N
|
||||
inv_N = nb.float32(1.0 / N)
|
||||
for y in nb.prange(H):
|
||||
for x in range(W):
|
||||
hits = 0
|
||||
for i in range(N):
|
||||
b = bins[i]
|
||||
mask = np.uint8(1) << b
|
||||
if (bit_active & mask) == 0:
|
||||
if hits + (N - i - 1) < min_req:
|
||||
break
|
||||
continue
|
||||
ddy = dy[i]
|
||||
yy = y + ddy
|
||||
if yy < 0 or yy >= H:
|
||||
if hits + (N - i - 1) < min_req:
|
||||
break
|
||||
continue
|
||||
ddx = dx[i]
|
||||
xx = x + ddx
|
||||
if xx < 0 or xx >= W:
|
||||
if hits + (N - i - 1) < min_req:
|
||||
break
|
||||
continue
|
||||
if spread[yy, xx] & mask:
|
||||
hits += 1
|
||||
else:
|
||||
if hits + (N - i - 1) < min_req:
|
||||
break
|
||||
acc[y, x] = nb.float32(hits) * inv_N
|
||||
return acc
|
||||
|
||||
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||
def _jit_score_bitmap_rescored(
|
||||
spread: np.ndarray, # uint8 (H, W)
|
||||
@@ -159,6 +271,122 @@ if HAS_NUMBA:
|
||||
acc[y, x] = 0.0
|
||||
return acc
|
||||
|
||||
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||
def _jit_top_max_per_variant(
|
||||
spread: np.ndarray, # uint8 (H, W)
|
||||
dx_flat: np.ndarray, # int32 (sum_N,)
|
||||
dy_flat: np.ndarray, # int32 (sum_N,)
|
||||
bins_flat: np.ndarray, # int8 (sum_N,)
|
||||
offsets: np.ndarray, # int32 (n_vars+1,) prefix sum
|
||||
bit_active: np.uint8,
|
||||
bg_per_variant: np.ndarray, # float32 (n_vars, H, W) - 1 per scala
|
||||
scale_idx: np.ndarray, # int32 (n_vars,) idx in bg_per_variant
|
||||
) -> np.ndarray:
|
||||
"""Batch: per ogni variante calcola max score (rescored bg), ritorna
|
||||
array float32 (n_vars,). Parallelismo prange ESTERNO sulle varianti
|
||||
elimina overhead di n_vars chiamate JIT separate (avg ~20us per
|
||||
chiamata su template piccoli) + pool thread Python.
|
||||
|
||||
Pensato per fase TOP del pruning quando n_vars >> n_threads.
|
||||
"""
|
||||
n_vars = offsets.shape[0] - 1
|
||||
H, W = spread.shape
|
||||
out = np.zeros(n_vars, dtype=np.float32)
|
||||
for vi in nb.prange(n_vars):
|
||||
i0 = offsets[vi]; i1 = offsets[vi + 1]
|
||||
N = i1 - i0
|
||||
if N == 0:
|
||||
out[vi] = -1.0
|
||||
continue
|
||||
si = scale_idx[vi]
|
||||
inv = nb.float32(1.0 / N)
|
||||
best = nb.float32(-1.0)
|
||||
for y in range(H):
|
||||
for x in range(W):
|
||||
s = nb.float32(0.0)
|
||||
for k in range(N):
|
||||
b = bins_flat[i0 + k]
|
||||
mask = np.uint8(1) << b
|
||||
if (bit_active & mask) == 0:
|
||||
continue
|
||||
ddy = dy_flat[i0 + k]
|
||||
yy = y + ddy
|
||||
if yy < 0 or yy >= H:
|
||||
continue
|
||||
ddx = dx_flat[i0 + k]
|
||||
xx = x + ddx
|
||||
if xx < 0 or xx >= W:
|
||||
continue
|
||||
if spread[yy, xx] & mask:
|
||||
s += nb.float32(1.0)
|
||||
s *= inv
|
||||
bgv = bg_per_variant[si, y, x]
|
||||
if bgv < 1.0:
|
||||
r = (s - bgv) / (1.0 - bgv + 1e-6)
|
||||
if r > best:
|
||||
best = r
|
||||
out[vi] = best if best > 0.0 else 0.0
|
||||
return out
|
||||
|
||||
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||
def _jit_score_bitmap_rescored_u16(
|
||||
spread: np.ndarray, # uint16 (H, W) - 16 bit di polarity-aware
|
||||
dx: np.ndarray, dy: np.ndarray, bins: np.ndarray,
|
||||
bit_active: np.uint16,
|
||||
bg: np.ndarray,
|
||||
) -> np.ndarray:
|
||||
"""Versione uint16 di _jit_score_bitmap_rescored per polarity 16-bin.
|
||||
|
||||
Identica logica ma mask = uint16(1) << b dove b in [0..15]
|
||||
(orientamento mod 2π invece di mod π).
|
||||
"""
|
||||
H, W = spread.shape
|
||||
N = dx.shape[0]
|
||||
acc = np.zeros((H, W), dtype=np.float32)
|
||||
for y in nb.prange(H):
|
||||
for i in range(N):
|
||||
b = bins[i]
|
||||
mask = np.uint16(1) << b
|
||||
if (bit_active & mask) == 0:
|
||||
continue
|
||||
ddy = dy[i]
|
||||
yy = y + ddy
|
||||
if yy < 0 or yy >= H:
|
||||
continue
|
||||
ddx = dx[i]
|
||||
x_lo = 0 if ddx >= 0 else -ddx
|
||||
x_hi = W if ddx <= 0 else W - ddx
|
||||
for x in range(x_lo, x_hi):
|
||||
if spread[yy, x + ddx] & mask:
|
||||
acc[y, x] += 1.0
|
||||
if N > 0:
|
||||
inv = 1.0 / N
|
||||
for y in nb.prange(H):
|
||||
for x in range(W):
|
||||
v = acc[y, x] * inv
|
||||
bgv = bg[y, x]
|
||||
if bgv < 1.0:
|
||||
r = (v - bgv) / (1.0 - bgv + 1e-6)
|
||||
acc[y, x] = r if r > 0.0 else 0.0
|
||||
else:
|
||||
acc[y, x] = 0.0
|
||||
return acc
|
||||
|
||||
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||
def _jit_popcount_density_u16(spread: np.ndarray) -> np.ndarray:
|
||||
"""Popcount per uint16 (16 bin polarity)."""
|
||||
H, W = spread.shape
|
||||
out = np.zeros((H, W), dtype=np.float32)
|
||||
for y in nb.prange(H):
|
||||
for x in range(W):
|
||||
v = spread[y, x]
|
||||
cnt = 0
|
||||
for b in range(16):
|
||||
if v & (np.uint16(1) << b):
|
||||
cnt += 1
|
||||
out[y, x] = float(cnt)
|
||||
return out
|
||||
|
||||
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||
def _jit_popcount_density(spread: np.ndarray) -> np.ndarray:
|
||||
"""Conta bit set per pixel: ritorna (H, W) float32 in [0..8]."""
|
||||
@@ -185,7 +413,25 @@ if HAS_NUMBA:
|
||||
_jit_score_bitmap(spread, dx, dy, b, np.uint8(0xFF))
|
||||
bg = np.zeros((32, 32), dtype=np.float32)
|
||||
_jit_score_bitmap_rescored(spread, dx, dy, b, np.uint8(0xFF), bg)
|
||||
_jit_score_bitmap_rescored_strided(
|
||||
spread, dx, dy, b, np.uint8(0xFF), bg, np.int32(2),
|
||||
)
|
||||
_jit_score_bitmap_greedy(
|
||||
spread, dx, dy, b, np.uint8(0xFF),
|
||||
np.float32(0.5), np.float32(0.8),
|
||||
)
|
||||
offsets = np.array([0, 1], dtype=np.int32)
|
||||
scale_idx = np.zeros(1, dtype=np.int32)
|
||||
bg_pv = np.zeros((1, 32, 32), dtype=np.float32)
|
||||
_jit_top_max_per_variant(
|
||||
spread, dx, dy, b, offsets, np.uint8(0xFF), bg_pv, scale_idx,
|
||||
)
|
||||
_jit_popcount_density(spread)
|
||||
spread16 = np.zeros((32, 32), dtype=np.uint16)
|
||||
_jit_score_bitmap_rescored_u16(
|
||||
spread16, dx, dy, b, np.uint16(0xFFFF), bg,
|
||||
)
|
||||
_jit_popcount_density_u16(spread16)
|
||||
|
||||
else: # pragma: no cover
|
||||
|
||||
@@ -198,6 +444,24 @@ else: # pragma: no cover
|
||||
def _jit_score_bitmap_rescored(spread, dx, dy, bins, bit_active, bg):
|
||||
raise RuntimeError("numba non disponibile")
|
||||
|
||||
def _jit_score_bitmap_rescored_strided(spread, dx, dy, bins, bit_active, bg, stride):
|
||||
raise RuntimeError("numba non disponibile")
|
||||
|
||||
def _jit_score_bitmap_greedy(spread, dx, dy, bins, bit_active, min_score, greediness):
|
||||
raise RuntimeError("numba non disponibile")
|
||||
|
||||
def _jit_top_max_per_variant(
|
||||
spread, dx_flat, dy_flat, bins_flat, offsets, bit_active,
|
||||
bg_per_variant, scale_idx,
|
||||
):
|
||||
raise RuntimeError("numba non disponibile")
|
||||
|
||||
def _jit_score_bitmap_rescored_u16(spread, dx, dy, bins, bit_active, bg):
|
||||
raise RuntimeError("numba non disponibile")
|
||||
|
||||
def _jit_popcount_density_u16(spread):
|
||||
raise RuntimeError("numba non disponibile")
|
||||
|
||||
def _jit_popcount_density(spread):
|
||||
raise RuntimeError("numba non disponibile")
|
||||
|
||||
@@ -228,28 +492,132 @@ def score_bitmap(
|
||||
|
||||
def score_bitmap_rescored(
|
||||
spread: np.ndarray, dx: np.ndarray, dy: np.ndarray, bins: np.ndarray,
|
||||
bit_active: int, bg: np.ndarray,
|
||||
bit_active: int, bg: np.ndarray, stride: int = 1,
|
||||
) -> np.ndarray:
|
||||
"""Score bitmap + rescore fusi in un solo pass (JIT)."""
|
||||
"""Score bitmap + rescore fusi in un solo pass (JIT).
|
||||
|
||||
Dispatch per dtype: uint16 → kernel polarity 16-bin, uint8 → kernel
|
||||
standard 8-bin (con eventuale stride > 1 per coarse top-level).
|
||||
"""
|
||||
if HAS_NUMBA and len(dx) > 0:
|
||||
return _jit_score_bitmap_rescored(
|
||||
np.ascontiguousarray(spread, dtype=np.uint8),
|
||||
np.ascontiguousarray(dx, dtype=np.int32),
|
||||
np.ascontiguousarray(dy, dtype=np.int32),
|
||||
np.ascontiguousarray(bins, dtype=np.int8),
|
||||
np.uint8(bit_active),
|
||||
np.ascontiguousarray(bg, dtype=np.float32),
|
||||
dx_c = np.ascontiguousarray(dx, dtype=np.int32)
|
||||
dy_c = np.ascontiguousarray(dy, dtype=np.int32)
|
||||
bins_c = np.ascontiguousarray(bins, dtype=np.int8)
|
||||
bg_c = np.ascontiguousarray(bg, dtype=np.float32)
|
||||
if spread.dtype == np.uint16:
|
||||
spread_c = np.ascontiguousarray(spread, dtype=np.uint16)
|
||||
return _jit_score_bitmap_rescored_u16(
|
||||
spread_c, dx_c, dy_c, bins_c, np.uint16(bit_active), bg_c,
|
||||
)
|
||||
# Fallback: chiamate separate
|
||||
spread_c = np.ascontiguousarray(spread, dtype=np.uint8)
|
||||
if stride > 1:
|
||||
return _jit_score_bitmap_rescored_strided(
|
||||
spread_c, dx_c, dy_c, bins_c, np.uint8(bit_active), bg_c,
|
||||
np.int32(stride),
|
||||
)
|
||||
return _jit_score_bitmap_rescored(
|
||||
spread_c, dx_c, dy_c, bins_c, np.uint8(bit_active), bg_c,
|
||||
)
|
||||
# Fallback: chiamate separate (stride ignorato in fallback)
|
||||
score = score_bitmap(spread, dx, dy, bins, bit_active)
|
||||
out = (score - bg) / (1.0 - bg + 1e-6)
|
||||
return np.maximum(0.0, out).astype(np.float32)
|
||||
|
||||
|
||||
def score_bitmap_greedy(
|
||||
spread: np.ndarray, dx: np.ndarray, dy: np.ndarray, bins: np.ndarray,
|
||||
bit_active: int, min_score: float, greediness: float,
|
||||
) -> np.ndarray:
|
||||
"""Score bitmap con early-exit greedy. Per coarse-pass aggressivo.
|
||||
|
||||
Non applica rescore background: usare quando la scena ha basso clutter
|
||||
o quando si vuole mass-prune varianti via top-level rapidamente.
|
||||
"""
|
||||
if HAS_NUMBA and len(dx) > 0:
|
||||
return _jit_score_bitmap_greedy(
|
||||
np.ascontiguousarray(spread, dtype=np.uint8),
|
||||
np.ascontiguousarray(dx, dtype=np.int32),
|
||||
np.ascontiguousarray(dy, dtype=np.int32),
|
||||
np.ascontiguousarray(bins, dtype=np.int8),
|
||||
np.uint8(bit_active),
|
||||
np.float32(min_score), np.float32(greediness),
|
||||
)
|
||||
# Fallback: kernel base senza early-exit
|
||||
return score_bitmap(spread, dx, dy, bins, bit_active)
|
||||
|
||||
|
||||
def top_max_per_variant(
|
||||
spread: np.ndarray,
|
||||
dx_list: list, dy_list: list, bin_list: list,
|
||||
bg_per_scale: dict,
|
||||
variant_scales: list,
|
||||
bit_active: int,
|
||||
) -> np.ndarray:
|
||||
"""Wrapper: prepara buffer flat e chiama kernel batch su tutte le varianti.
|
||||
|
||||
Parallelismo Numba prange-esterno sulle varianti (n_vars >> n_threads
|
||||
tipicamente per top-pruning) → meglio del thread-pool Python che paga
|
||||
overhead di n_vars chiamate JIT separate.
|
||||
"""
|
||||
if not HAS_NUMBA or len(dx_list) == 0:
|
||||
return np.array([], dtype=np.float32)
|
||||
n_vars = len(dx_list)
|
||||
sizes = [len(d) for d in dx_list]
|
||||
offsets = np.zeros(n_vars + 1, dtype=np.int32)
|
||||
offsets[1:] = np.cumsum(sizes)
|
||||
total = int(offsets[-1])
|
||||
dx_flat = np.empty(total, dtype=np.int32)
|
||||
dy_flat = np.empty(total, dtype=np.int32)
|
||||
bins_flat = np.empty(total, dtype=np.int8)
|
||||
for vi, (dx, dy, bn) in enumerate(zip(dx_list, dy_list, bin_list)):
|
||||
i0 = int(offsets[vi]); i1 = int(offsets[vi + 1])
|
||||
dx_flat[i0:i1] = dx
|
||||
dy_flat[i0:i1] = dy
|
||||
bins_flat[i0:i1] = bn
|
||||
# bg per variante: indicizzato per scala
|
||||
scales_unique = sorted(bg_per_scale.keys())
|
||||
scale_to_idx = {s: i for i, s in enumerate(scales_unique)}
|
||||
H, W = spread.shape
|
||||
bg_pv = np.empty((len(scales_unique), H, W), dtype=np.float32)
|
||||
for s, idx in scale_to_idx.items():
|
||||
bg_pv[idx] = bg_per_scale[s]
|
||||
scale_idx = np.array(
|
||||
[scale_to_idx[s] for s in variant_scales], dtype=np.int32,
|
||||
)
|
||||
return _jit_top_max_per_variant(
|
||||
np.ascontiguousarray(spread, dtype=np.uint8),
|
||||
dx_flat, dy_flat, bins_flat, offsets, np.uint8(bit_active),
|
||||
bg_pv, scale_idx,
|
||||
)
|
||||
|
||||
|
||||
_HAS_NP_BITCOUNT = hasattr(np, "bitwise_count")
|
||||
|
||||
|
||||
def popcount_density(spread: np.ndarray) -> np.ndarray:
|
||||
"""Conta bit set per pixel.
|
||||
|
||||
Order:
|
||||
1) Numba JIT parallel (preferito: piu veloce su 1080p, 0.5ms vs 1.6ms)
|
||||
2) numpy.bitwise_count (NumPy 2.0+, SIMD ma single-thread)
|
||||
3) Fallback numpy bit-shift puro
|
||||
"""
|
||||
if spread.dtype == np.uint16:
|
||||
spread_c = np.ascontiguousarray(spread, dtype=np.uint16)
|
||||
if HAS_NUMBA:
|
||||
return _jit_popcount_density(np.ascontiguousarray(spread, dtype=np.uint8))
|
||||
# Fallback
|
||||
return _jit_popcount_density_u16(spread_c)
|
||||
if _HAS_NP_BITCOUNT:
|
||||
return np.bitwise_count(spread_c).astype(np.float32, copy=False)
|
||||
H, W = spread_c.shape
|
||||
out = np.zeros((H, W), dtype=np.float32)
|
||||
for b in range(16):
|
||||
out += ((spread_c >> b) & 1).astype(np.float32)
|
||||
return out
|
||||
spread_c = np.ascontiguousarray(spread, dtype=np.uint8)
|
||||
if HAS_NUMBA:
|
||||
return _jit_popcount_density(spread_c)
|
||||
if _HAS_NP_BITCOUNT:
|
||||
return np.bitwise_count(spread_c).astype(np.float32, copy=False)
|
||||
H, W = spread.shape
|
||||
out = np.zeros((H, W), dtype=np.float32)
|
||||
for b in range(8):
|
||||
|
||||
+26
-5
@@ -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,7 +221,12 @@ 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 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
|
||||
@@ -220,12 +238,15 @@ def auto_tune(template_bgr: np.ndarray, mask: np.ndarray | None = None) -> dict:
|
||||
else:
|
||||
min_score = 0.45
|
||||
|
||||
# angle step: 5° default; se simmetria, mantengo step ma range ridotto
|
||||
angle_step = 5.0
|
||||
# angle step adattivo (Halcon-style): atan(2/max_side) deg, clampato.
|
||||
# Template grande → step fine (rotazione minima visibile su perimetro).
|
||||
# Template piccolo → step grosso (over-sampling = sprecato).
|
||||
max_side = max(h, w)
|
||||
angle_step = float(np.clip(np.degrees(np.arctan2(2.0, max_side)), 1.0, 8.0))
|
||||
|
||||
result = {
|
||||
"backend": "line",
|
||||
"angle_min": 0.0,
|
||||
"angle_min": angle_min,
|
||||
"angle_max": angle_max,
|
||||
"angle_step": angle_step,
|
||||
"scale_min": 1.0,
|
||||
|
||||
+836
-47
File diff suppressed because it is too large
Load Diff
+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