Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 27a0ef1a45 |
+83
-10
@@ -110,6 +110,63 @@ if HAS_NUMBA:
|
|||||||
acc[y, x] *= inv
|
acc[y, x] *= inv
|
||||||
return acc
|
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)
|
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||||
def _jit_score_bitmap_rescored(
|
def _jit_score_bitmap_rescored(
|
||||||
spread: np.ndarray, # uint8 (H, W)
|
spread: np.ndarray, # uint8 (H, W)
|
||||||
@@ -185,6 +242,9 @@ if HAS_NUMBA:
|
|||||||
_jit_score_bitmap(spread, dx, dy, b, np.uint8(0xFF))
|
_jit_score_bitmap(spread, dx, dy, b, np.uint8(0xFF))
|
||||||
bg = np.zeros((32, 32), dtype=np.float32)
|
bg = np.zeros((32, 32), dtype=np.float32)
|
||||||
_jit_score_bitmap_rescored(spread, dx, dy, b, np.uint8(0xFF), bg)
|
_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_popcount_density(spread)
|
_jit_popcount_density(spread)
|
||||||
|
|
||||||
else: # pragma: no cover
|
else: # pragma: no cover
|
||||||
@@ -198,6 +258,9 @@ else: # pragma: no cover
|
|||||||
def _jit_score_bitmap_rescored(spread, dx, dy, bins, bit_active, bg):
|
def _jit_score_bitmap_rescored(spread, dx, dy, bins, bit_active, bg):
|
||||||
raise RuntimeError("numba non disponibile")
|
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_popcount_density(spread):
|
def _jit_popcount_density(spread):
|
||||||
raise RuntimeError("numba non disponibile")
|
raise RuntimeError("numba non disponibile")
|
||||||
|
|
||||||
@@ -228,19 +291,29 @@ def score_bitmap(
|
|||||||
|
|
||||||
def score_bitmap_rescored(
|
def score_bitmap_rescored(
|
||||||
spread: np.ndarray, dx: np.ndarray, dy: np.ndarray, bins: np.ndarray,
|
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:
|
) -> np.ndarray:
|
||||||
"""Score bitmap + rescore fusi in un solo pass (JIT)."""
|
"""Score bitmap + rescore fusi in un solo pass (JIT).
|
||||||
|
|
||||||
|
stride > 1: valuta solo pixel su griglia stride×stride. Le celle non
|
||||||
|
valutate restano 0 nello score map. Pensato per coarse-pass al top
|
||||||
|
della piramide; il refinement full-res poi recupera precisione.
|
||||||
|
"""
|
||||||
if HAS_NUMBA and len(dx) > 0:
|
if HAS_NUMBA and len(dx) > 0:
|
||||||
return _jit_score_bitmap_rescored(
|
spread_c = np.ascontiguousarray(spread, dtype=np.uint8)
|
||||||
np.ascontiguousarray(spread, dtype=np.uint8),
|
dx_c = np.ascontiguousarray(dx, dtype=np.int32)
|
||||||
np.ascontiguousarray(dx, dtype=np.int32),
|
dy_c = np.ascontiguousarray(dy, dtype=np.int32)
|
||||||
np.ascontiguousarray(dy, dtype=np.int32),
|
bins_c = np.ascontiguousarray(bins, dtype=np.int8)
|
||||||
np.ascontiguousarray(bins, dtype=np.int8),
|
bg_c = np.ascontiguousarray(bg, dtype=np.float32)
|
||||||
np.uint8(bit_active),
|
if stride > 1:
|
||||||
np.ascontiguousarray(bg, dtype=np.float32),
|
return _jit_score_bitmap_rescored_strided(
|
||||||
|
spread_c, dx_c, dy_c, bins_c, np.uint8(bit_active), bg_c,
|
||||||
|
np.int32(stride),
|
||||||
)
|
)
|
||||||
# Fallback: chiamate separate
|
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)
|
score = score_bitmap(spread, dx, dy, bins, bit_active)
|
||||||
out = (score - bg) / (1.0 - bg + 1e-6)
|
out = (score - bg) / (1.0 - bg + 1e-6)
|
||||||
return np.maximum(0.0, out).astype(np.float32)
|
return np.maximum(0.0, out).astype(np.float32)
|
||||||
|
|||||||
+9
-28
@@ -573,8 +573,8 @@ class LineShapeMatcher:
|
|||||||
verify_ncc: bool = True,
|
verify_ncc: bool = True,
|
||||||
verify_threshold: float = 0.4,
|
verify_threshold: float = 0.4,
|
||||||
coarse_angle_factor: int = 2,
|
coarse_angle_factor: int = 2,
|
||||||
|
coarse_stride: int = 1,
|
||||||
scale_penalty: float = 0.0,
|
scale_penalty: float = 0.0,
|
||||||
search_roi: tuple[int, int, int, int] | None = None,
|
|
||||||
) -> 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:
|
||||||
@@ -582,30 +582,11 @@ class LineShapeMatcher:
|
|||||||
Utile se l'operatore vuole che match "identico al template anche per
|
Utile se l'operatore vuole che match "identico al template anche per
|
||||||
dimensione" abbia score più alto di match "stessa forma, dimensione
|
dimensione" abbia score più alto di match "stessa forma, dimensione
|
||||||
diversa". scale_penalty=0 (default) = comportamento shape puro.
|
diversa". scale_penalty=0 (default) = comportamento shape puro.
|
||||||
|
|
||||||
search_roi: (x, y, w, h) limita la ricerca a una regione della scena.
|
|
||||||
Equivalente a Halcon set_aoi: il matching opera su crop locale e le
|
|
||||||
coordinate output sono ri-traslate al sistema scena originale. Usare
|
|
||||||
quando si conosce a priori l'area in cui il pezzo può apparire (es.
|
|
||||||
feeder a posizione fissa) → costo proporzionale a w·h invece di W·H.
|
|
||||||
"""
|
"""
|
||||||
if not self.variants:
|
if not self.variants:
|
||||||
raise RuntimeError("Matcher non addestrato: chiamare train() prima.")
|
raise RuntimeError("Matcher non addestrato: chiamare train() prima.")
|
||||||
|
|
||||||
gray_full = self._to_gray(scene_bgr)
|
gray0 = self._to_gray(scene_bgr)
|
||||||
# Applica ROI di ricerca: restringe scena a crop, ricorda offset per
|
|
||||||
# ri-traslare le coordinate dei match a fine pipeline.
|
|
||||||
if search_roi is not None:
|
|
||||||
rx, ry, rw, rh = search_roi
|
|
||||||
H_s, W_s = gray_full.shape
|
|
||||||
rx = max(0, int(rx)); ry = max(0, int(ry))
|
|
||||||
rw = max(1, min(int(rw), W_s - rx))
|
|
||||||
rh = max(1, min(int(rh), H_s - ry))
|
|
||||||
gray0 = gray_full[ry:ry + rh, rx:rx + rw]
|
|
||||||
roi_offset = (rx, ry)
|
|
||||||
else:
|
|
||||||
gray0 = gray_full
|
|
||||||
roi_offset = (0, 0)
|
|
||||||
grays = [gray0]
|
grays = [gray0]
|
||||||
for _ in range(self.pyramid_levels - 1):
|
for _ in range(self.pyramid_levels - 1):
|
||||||
grays.append(cv2.pyrDown(grays[-1]))
|
grays.append(cv2.pyrDown(grays[-1]))
|
||||||
@@ -665,13 +646,16 @@ class LineShapeMatcher:
|
|||||||
end = min(n, i + half + 1)
|
end = min(n, i + half + 1)
|
||||||
neighbor_map[vi_c] = vi_sorted[start:end]
|
neighbor_map[vi_c] = vi_sorted[start:end]
|
||||||
|
|
||||||
# Pruning varianti via top-level (parallelizzato) - solo coarse
|
# Pruning varianti via top-level (parallelizzato) - solo coarse.
|
||||||
|
# coarse_stride > 1: valuta solo 1 pixel ogni stride, ~stride² speed-up.
|
||||||
|
cs = max(1, int(coarse_stride))
|
||||||
|
|
||||||
def _top_score(vi: int) -> tuple[int, float]:
|
def _top_score(vi: int) -> tuple[int, float]:
|
||||||
var = self.variants[vi]
|
var = self.variants[vi]
|
||||||
lvl = var.levels[min(top, len(var.levels) - 1)]
|
lvl = var.levels[min(top, len(var.levels) - 1)]
|
||||||
score = _jit_score_bitmap_rescored(
|
score = _jit_score_bitmap_rescored(
|
||||||
spread_top, lvl.dx, lvl.dy, lvl.bin, bit_active_top,
|
spread_top, lvl.dx, lvl.dy, lvl.bin, bit_active_top,
|
||||||
bg_cache_top[var.scale],
|
bg_cache_top[var.scale], stride=cs,
|
||||||
)
|
)
|
||||||
return vi, float(score.max()) if score.size else -1.0
|
return vi, float(score.max()) if score.size else -1.0
|
||||||
|
|
||||||
@@ -830,11 +814,8 @@ class LineShapeMatcher:
|
|||||||
if ncc < verify_threshold:
|
if ncc < verify_threshold:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Ri-traslo coord da spazio crop ROI a spazio scena originale.
|
|
||||||
cx_out = cx_f + roi_offset[0]
|
|
||||||
cy_out = cy_f + roi_offset[1]
|
|
||||||
poly = _oriented_bbox_polygon(
|
poly = _oriented_bbox_polygon(
|
||||||
cx_out, cy_out, tw * var.scale, th * var.scale, ang_f,
|
cx_f, cy_f, tw * var.scale, th * var.scale, ang_f,
|
||||||
)
|
)
|
||||||
# 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:
|
||||||
@@ -842,7 +823,7 @@ class LineShapeMatcher:
|
|||||||
0.0, 1.0 - scale_penalty * abs(var.scale - 1.0)
|
0.0, 1.0 - scale_penalty * abs(var.scale - 1.0)
|
||||||
)
|
)
|
||||||
kept.append(Match(
|
kept.append(Match(
|
||||||
cx=cx_out, cy=cy_out,
|
cx=cx_f, cy=cy_f,
|
||||||
angle_deg=ang_f,
|
angle_deg=ang_f,
|
||||||
scale=var.scale,
|
scale=var.scale,
|
||||||
score=score_f,
|
score=score_f,
|
||||||
|
|||||||
Reference in New Issue
Block a user