Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6ebb08e7a2 | |||
| 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 | |||
| 4419c237b2 | |||
| f00cf9b621 | |||
| 4b7271094b | |||
| 746d1668c6 | |||
| d9a40952c4 | |||
| 6db2086ead | |||
| 27a0ef1a45 | |||
| ba4024d252 |
+263
-9
@@ -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)
|
||||
@@ -216,6 +328,65 @@ if HAS_NUMBA:
|
||||
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]."""
|
||||
@@ -242,6 +413,13 @@ 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)
|
||||
@@ -249,6 +427,11 @@ if HAS_NUMBA:
|
||||
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
|
||||
|
||||
@@ -261,12 +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")
|
||||
|
||||
@@ -297,22 +492,58 @@ 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:
|
||||
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,
|
||||
)
|
||||
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.ascontiguousarray(bg, dtype=np.float32),
|
||||
np.float32(min_score), np.float32(greediness),
|
||||
)
|
||||
# Fallback: chiamate separate
|
||||
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)
|
||||
# Fallback: kernel base senza early-exit
|
||||
return score_bitmap(spread, dx, dy, bins, bit_active)
|
||||
|
||||
|
||||
def top_max_per_variant(
|
||||
@@ -360,10 +591,33 @@ def top_max_per_variant(
|
||||
)
|
||||
|
||||
|
||||
_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,
|
||||
|
||||
+924
-47
File diff suppressed because it is too large
Load Diff
+101
-3
@@ -48,6 +48,10 @@ IMAGES_DIR = Path(_images_dir_raw)
|
||||
if not IMAGES_DIR.is_absolute():
|
||||
IMAGES_DIR = PROJECT_ROOT / IMAGES_DIR
|
||||
|
||||
# Cartella ricette pre-trained (V feature: save/load matcher)
|
||||
RECIPES_DIR = PROJECT_ROOT / "recipes"
|
||||
RECIPES_DIR.mkdir(exist_ok=True)
|
||||
|
||||
from pm2d.line_matcher import LineShapeMatcher, Match
|
||||
from pm2d.auto_tune import auto_tune
|
||||
|
||||
@@ -249,9 +253,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
|
||||
}
|
||||
|
||||
|
||||
@@ -267,6 +271,20 @@ class SimpleMatchParams(BaseModel):
|
||||
penalita_scala: float = 0.0 # 0 = score shape invariante, >0 = penalizza scala != 1
|
||||
min_score: float = 0.65
|
||||
max_matches: int = 25
|
||||
# --- Halcon-mode flags (default off = backward compat) ---
|
||||
# Init-time (richiede ri-train se cambiato)
|
||||
use_polarity: bool = False # F: 16 bin orientation mod 2pi
|
||||
use_gpu: bool = False # R: OpenCL UMat (silent fallback)
|
||||
# Find-time (no retrain)
|
||||
min_recall: float = 0.0 # M: filtra match con poche feature combaciate
|
||||
use_soft_score: bool = False # Y: cosine sim continua dei gradients
|
||||
subpixel_lm: bool = False # Z: precisione 0.05 px
|
||||
nms_iou_threshold: float = 0.3 # A: IoU bbox poligonale
|
||||
coarse_stride: int = 1 # sub-sampling top-level (>=1)
|
||||
pyramid_propagate: bool = False # propagazione candidati top->full
|
||||
greediness: float = 0.0 # early-exit kernel (0..1)
|
||||
refine_pose_joint: bool = False # Nelder-Mead 3D (cx, cy, angle)
|
||||
search_roi: list[int] | None = None # [x, y, w, h] limita area
|
||||
|
||||
|
||||
def _simple_to_technical(
|
||||
@@ -526,6 +544,9 @@ def match_simple(p: SimpleMatchParams):
|
||||
tech = _simple_to_technical(p, roi_img)
|
||||
|
||||
key = _matcher_cache_key(roi_img, tech)
|
||||
# Halcon-mode init params: incidono sul training, includere in cache key
|
||||
halcon_init_key = f"|pol={p.use_polarity}|gpu={p.use_gpu}"
|
||||
key = key + halcon_init_key
|
||||
m = _cache_get_matcher(key)
|
||||
if m is None:
|
||||
m = LineShapeMatcher(
|
||||
@@ -537,17 +558,30 @@ def match_simple(p: SimpleMatchParams):
|
||||
scale_step=tech["scale_step"],
|
||||
spread_radius=tech["spread_radius"],
|
||||
pyramid_levels=tech["pyramid_levels"],
|
||||
use_polarity=p.use_polarity,
|
||||
use_gpu=p.use_gpu,
|
||||
)
|
||||
t0 = time.time(); n = m.train(roi_img); t_train = time.time() - t0
|
||||
_cache_put_matcher(key, m)
|
||||
else:
|
||||
n = len(m.variants); t_train = 0.0
|
||||
nms = tech["nms_radius"] if tech["nms_radius"] > 0 else None
|
||||
search_roi_t = tuple(p.search_roi) if p.search_roi else None
|
||||
t0 = time.time()
|
||||
matches = m.find(
|
||||
scene, min_score=tech["min_score"], max_matches=tech["max_matches"],
|
||||
nms_radius=nms, verify_threshold=tech["verify_threshold"],
|
||||
scale_penalty=tech.get("scale_penalty", 0.0),
|
||||
# Halcon-mode flags
|
||||
min_recall=p.min_recall,
|
||||
use_soft_score=p.use_soft_score,
|
||||
subpixel_lm=p.subpixel_lm,
|
||||
nms_iou_threshold=p.nms_iou_threshold,
|
||||
coarse_stride=p.coarse_stride,
|
||||
pyramid_propagate=p.pyramid_propagate,
|
||||
greediness=p.greediness,
|
||||
refine_pose_joint=p.refine_pose_joint,
|
||||
search_roi=search_roi_t,
|
||||
)
|
||||
t_find = time.time() - t0
|
||||
|
||||
@@ -576,6 +610,70 @@ def tune(p: TuneParams):
|
||||
return {k: v for k, v in t.items() if not k.startswith("_")}
|
||||
|
||||
|
||||
# --- V: Save/Load ricette pre-trained ---
|
||||
|
||||
class SaveRecipeParams(BaseModel):
|
||||
model_id: str
|
||||
scene_id: str | None = None
|
||||
roi: list[int]
|
||||
# Riusa stessi param simple per training equivalente
|
||||
tipo: str = "intero"
|
||||
simmetria: str = "nessuna"
|
||||
scala: str = "fissa"
|
||||
precisione: str = "normale"
|
||||
use_polarity: bool = False
|
||||
use_gpu: bool = False
|
||||
name: str # nome file ricetta (no path)
|
||||
|
||||
|
||||
@app.post("/recipes")
|
||||
def save_recipe(p: SaveRecipeParams):
|
||||
"""Allena matcher e salva su disco come ricetta riutilizzabile."""
|
||||
model = _load_image(p.model_id)
|
||||
if model is None:
|
||||
raise HTTPException(404, "Modello non trovato")
|
||||
x, y, w, h = p.roi
|
||||
roi_img = model[y:y + h, x:x + w]
|
||||
sp = SimpleMatchParams(
|
||||
model_id=p.model_id, scene_id=p.scene_id or p.model_id, roi=p.roi,
|
||||
tipo=p.tipo, simmetria=p.simmetria, scala=p.scala,
|
||||
precisione=p.precisione,
|
||||
use_polarity=p.use_polarity, use_gpu=p.use_gpu,
|
||||
)
|
||||
tech = _simple_to_technical(sp, roi_img)
|
||||
m = LineShapeMatcher(
|
||||
num_features=tech["num_features"],
|
||||
weak_grad=tech["weak_grad"], strong_grad=tech["strong_grad"],
|
||||
angle_range_deg=(tech["angle_min"], tech["angle_max"]),
|
||||
angle_step_deg=tech["angle_step"],
|
||||
scale_range=(tech["scale_min"], tech["scale_max"]),
|
||||
scale_step=tech["scale_step"],
|
||||
spread_radius=tech["spread_radius"],
|
||||
pyramid_levels=tech["pyramid_levels"],
|
||||
use_polarity=p.use_polarity,
|
||||
use_gpu=p.use_gpu,
|
||||
)
|
||||
m.train(roi_img)
|
||||
safe_name = "".join(c for c in p.name if c.isalnum() or c in "._-")
|
||||
if not safe_name:
|
||||
raise HTTPException(400, "Nome ricetta non valido")
|
||||
if not safe_name.endswith(".npz"):
|
||||
safe_name += ".npz"
|
||||
target = RECIPES_DIR / safe_name
|
||||
m.save_model(str(target))
|
||||
return {"name": safe_name, "size": target.stat().st_size,
|
||||
"n_variants": len(m.variants)}
|
||||
|
||||
|
||||
@app.get("/recipes")
|
||||
def list_recipes():
|
||||
files = []
|
||||
if RECIPES_DIR.is_dir():
|
||||
for f in sorted(RECIPES_DIR.glob("*.npz")):
|
||||
files.append({"name": f.name, "size": f.stat().st_size})
|
||||
return {"files": files, "dir": str(RECIPES_DIR)}
|
||||
|
||||
|
||||
# Mount static
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
|
||||
|
||||
+82
-4
@@ -52,6 +52,39 @@ function readUserParams() {
|
||||
document.getElementById("p-penalita-scala").value),
|
||||
min_score: parseFloat(document.getElementById("p-min-score").value),
|
||||
max_matches: parseInt(document.getElementById("p-max-matches").value, 10),
|
||||
...readHalconFlags(),
|
||||
};
|
||||
}
|
||||
|
||||
function readHalconFlags() {
|
||||
// Halcon-mode toggle: tutti i flag default-off, esposti via "Modalità Halcon"
|
||||
const $cb = (id) => document.getElementById(id)?.checked ?? false;
|
||||
const $num = (id, def) => {
|
||||
const v = parseFloat(document.getElementById(id)?.value);
|
||||
return Number.isFinite(v) ? v : def;
|
||||
};
|
||||
const $int = (id, def) => {
|
||||
const v = parseInt(document.getElementById(id)?.value, 10);
|
||||
return Number.isFinite(v) ? v : def;
|
||||
};
|
||||
const roiStr = document.getElementById("hc-search-roi")?.value.trim() ?? "";
|
||||
let search_roi = null;
|
||||
if (roiStr) {
|
||||
const p = roiStr.split(/[ ,;]+/).map((x) => parseInt(x, 10));
|
||||
if (p.length === 4 && p.every((v) => Number.isFinite(v))) search_roi = p;
|
||||
}
|
||||
return {
|
||||
use_polarity: $cb("hc-use-polarity"),
|
||||
use_gpu: $cb("hc-use-gpu"),
|
||||
use_soft_score: $cb("hc-soft-score"),
|
||||
subpixel_lm: $cb("hc-subpixel-lm"),
|
||||
refine_pose_joint: $cb("hc-refine-joint"),
|
||||
pyramid_propagate: $cb("hc-pyr-propagate"),
|
||||
min_recall: $num("hc-min-recall", 0),
|
||||
nms_iou_threshold: $num("hc-nms-iou", 0.3),
|
||||
greediness: $num("hc-greediness", 0),
|
||||
coarse_stride: $int("hc-coarse-stride", 1),
|
||||
search_roi: search_roi,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -294,12 +327,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 +345,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 {
|
||||
@@ -362,6 +400,44 @@ function setStatus(s) {
|
||||
}
|
||||
|
||||
// ---------- Init ----------
|
||||
// ---------- V: Save recipe ----------
|
||||
async function saveRecipe() {
|
||||
if (!state.model || !state.roi) {
|
||||
alert("Seleziona modello e disegna ROI prima di salvare la ricetta.");
|
||||
return;
|
||||
}
|
||||
const name = document.getElementById("hc-recipe-name").value.trim();
|
||||
if (!name) {
|
||||
alert("Inserisci un nome per la ricetta.");
|
||||
return;
|
||||
}
|
||||
const user = readUserParams();
|
||||
const body = {
|
||||
model_id: state.model.id,
|
||||
scene_id: state.scene?.id || state.model.id,
|
||||
roi: state.roi,
|
||||
tipo: user.tipo,
|
||||
simmetria: user.simmetria,
|
||||
scala: user.scala,
|
||||
precisione: user.precisione,
|
||||
use_polarity: user.use_polarity,
|
||||
use_gpu: user.use_gpu,
|
||||
name: name,
|
||||
};
|
||||
try {
|
||||
const r = await fetch("/recipes", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!r.ok) throw new Error(await r.text());
|
||||
const j = await r.json();
|
||||
alert(`Ricetta salvata: ${j.name}\n${j.n_variants} varianti, ${j.size} bytes`);
|
||||
} catch (e) {
|
||||
alert(`Errore salvataggio: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("DOMContentLoaded", async () => {
|
||||
buildAdvancedForm();
|
||||
setupROI();
|
||||
@@ -389,6 +465,8 @@ window.addEventListener("DOMContentLoaded", async () => {
|
||||
e.target.value = ""; // consente re-upload stesso file
|
||||
});
|
||||
document.getElementById("btn-match").addEventListener("click", doMatch);
|
||||
document.getElementById("btn-save-recipe").addEventListener("click",
|
||||
saveRecipe);
|
||||
const slider = document.getElementById("p-min-score");
|
||||
slider.addEventListener("input", (e) => {
|
||||
document.getElementById("v-score").textContent =
|
||||
|
||||
@@ -129,6 +129,67 @@
|
||||
<input type="number" id="p-max-matches" value="25" min="1" max="200">
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary>Modalità Halcon</summary>
|
||||
<div class="halcon-grid">
|
||||
<label class="hc-row" title="16-bin orientation polarity-aware (mod 2π)">
|
||||
<input type="checkbox" id="hc-use-polarity">
|
||||
<span>Polarity 16-bin (F)</span>
|
||||
</label>
|
||||
<label class="hc-row" title="Score continuo cos(θ_t-θ_s) invece di bin">
|
||||
<input type="checkbox" id="hc-soft-score">
|
||||
<span>Soft-margin score (Y)</span>
|
||||
</label>
|
||||
<label class="hc-row" title="Sub-pixel refinement gradient field LM">
|
||||
<input type="checkbox" id="hc-subpixel-lm">
|
||||
<span>Sub-pixel LM 0.05 px (Z)</span>
|
||||
</label>
|
||||
<label class="hc-row" title="Refine congiunto Nelder-Mead (cx,cy,θ)">
|
||||
<input type="checkbox" id="hc-refine-joint">
|
||||
<span>Refine pose joint</span>
|
||||
</label>
|
||||
<label class="hc-row" title="Pyramid candidates propagation">
|
||||
<input type="checkbox" id="hc-pyr-propagate">
|
||||
<span>Pyramid propagate</span>
|
||||
</label>
|
||||
<label class="hc-row" title="OpenCL GPU offload (silent fallback CPU)">
|
||||
<input type="checkbox" id="hc-use-gpu">
|
||||
<span>GPU OpenCL (R)</span>
|
||||
</label>
|
||||
|
||||
<div class="hc-row hc-num">
|
||||
<label>Min recall (M)</label>
|
||||
<input type="number" id="hc-min-recall" value="0.0" min="0" max="1" step="0.05">
|
||||
</div>
|
||||
<div class="hc-row hc-num">
|
||||
<label>NMS IoU thr (A)</label>
|
||||
<input type="number" id="hc-nms-iou" value="0.3" min="0" max="1" step="0.05">
|
||||
</div>
|
||||
<div class="hc-row hc-num">
|
||||
<label>Greediness</label>
|
||||
<input type="number" id="hc-greediness" value="0.0" min="0" max="1" step="0.1">
|
||||
</div>
|
||||
<div class="hc-row hc-num">
|
||||
<label>Coarse stride</label>
|
||||
<input type="number" id="hc-coarse-stride" value="1" min="1" max="4" step="1">
|
||||
</div>
|
||||
<div class="hc-row hc-num" style="grid-column:1/-1">
|
||||
<label title="Limita area di ricerca scena: x,y,w,h (vuoto = tutta scena)">
|
||||
Search ROI (x,y,w,h)
|
||||
</label>
|
||||
<input type="text" id="hc-search-roi" placeholder="es. 100,50,800,400">
|
||||
</div>
|
||||
|
||||
<div class="hc-row" style="grid-column:1/-1; border-top:1px solid #444; padding-top:8px">
|
||||
<label>Ricetta pre-trained (V)</label>
|
||||
<div style="display:flex; gap:6px; margin-top:4px">
|
||||
<input type="text" id="hc-recipe-name" placeholder="nome_ricetta" style="flex:1">
|
||||
<button class="btn" id="btn-save-recipe" type="button">💾 Salva</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Avanzate</summary>
|
||||
<div id="adv-form"></div>
|
||||
|
||||
@@ -156,3 +156,20 @@ footer h2 {
|
||||
}
|
||||
|
||||
#col-model, #col-scene { min-width: 0; }
|
||||
|
||||
/* Halcon-mode panel */
|
||||
.halcon-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 6px 12px;
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.hc-row {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
}
|
||||
.hc-row.hc-num {
|
||||
flex-direction: column; align-items: flex-start;
|
||||
}
|
||||
.hc-row.hc-num label { font-size: 11px; color: #aaa; }
|
||||
.hc-row.hc-num input { width: 100%; }
|
||||
|
||||
Reference in New Issue
Block a user