Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6704d66cd5 |
@@ -159,6 +159,63 @@ if HAS_NUMBA:
|
|||||||
acc[y, x] = 0.0
|
acc[y, x] = 0.0
|
||||||
return acc
|
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)
|
@nb.njit(cache=True, parallel=True, fastmath=True, boundscheck=False)
|
||||||
def _jit_popcount_density(spread: np.ndarray) -> np.ndarray:
|
def _jit_popcount_density(spread: np.ndarray) -> np.ndarray:
|
||||||
"""Conta bit set per pixel: ritorna (H, W) float32 in [0..8]."""
|
"""Conta bit set per pixel: ritorna (H, W) float32 in [0..8]."""
|
||||||
@@ -185,6 +242,12 @@ 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)
|
||||||
|
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)
|
_jit_popcount_density(spread)
|
||||||
|
|
||||||
else: # pragma: no cover
|
else: # pragma: no cover
|
||||||
@@ -198,6 +261,12 @@ 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_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_popcount_density(spread):
|
def _jit_popcount_density(spread):
|
||||||
raise RuntimeError("numba non disponibile")
|
raise RuntimeError("numba non disponibile")
|
||||||
|
|
||||||
@@ -246,6 +315,51 @@ def score_bitmap_rescored(
|
|||||||
return np.maximum(0.0, out).astype(np.float32)
|
return np.maximum(0.0, out).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def popcount_density(spread: np.ndarray) -> np.ndarray:
|
def popcount_density(spread: np.ndarray) -> np.ndarray:
|
||||||
if HAS_NUMBA:
|
if HAS_NUMBA:
|
||||||
return _jit_popcount_density(np.ascontiguousarray(spread, dtype=np.uint8))
|
return _jit_popcount_density(np.ascontiguousarray(spread, dtype=np.uint8))
|
||||||
|
|||||||
+28
-65
@@ -40,6 +40,7 @@ from pm2d._jit_kernels import (
|
|||||||
score_by_shift as _jit_score_by_shift,
|
score_by_shift as _jit_score_by_shift,
|
||||||
score_bitmap as _jit_score_bitmap,
|
score_bitmap as _jit_score_bitmap,
|
||||||
score_bitmap_rescored as _jit_score_bitmap_rescored,
|
score_bitmap_rescored as _jit_score_bitmap_rescored,
|
||||||
|
top_max_per_variant as _jit_top_max_per_variant,
|
||||||
popcount_density as _jit_popcount,
|
popcount_density as _jit_popcount,
|
||||||
HAS_NUMBA,
|
HAS_NUMBA,
|
||||||
)
|
)
|
||||||
@@ -574,8 +575,7 @@ class LineShapeMatcher:
|
|||||||
verify_threshold: float = 0.4,
|
verify_threshold: float = 0.4,
|
||||||
coarse_angle_factor: int = 2,
|
coarse_angle_factor: int = 2,
|
||||||
scale_penalty: float = 0.0,
|
scale_penalty: float = 0.0,
|
||||||
pyramid_propagate: bool = True,
|
batch_top: bool = False,
|
||||||
propagate_topk: int = 8,
|
|
||||||
) -> 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:
|
||||||
@@ -647,12 +647,7 @@ 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).
|
# Pruning varianti via top-level (parallelizzato) - solo coarse
|
||||||
# Quando pyramid_propagate=True ritorna anche le top-K posizioni
|
|
||||||
# del picco (in coord top-level) per restringere la fase full-res
|
|
||||||
# a piccoli crop attorno ai candidati (vs intera scena).
|
|
||||||
peaks_by_vi: dict[int, list[tuple[int, int, float]]] = {}
|
|
||||||
|
|
||||||
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)]
|
||||||
@@ -660,27 +655,29 @@ class LineShapeMatcher:
|
|||||||
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],
|
||||||
)
|
)
|
||||||
if score.size == 0:
|
return vi, float(score.max()) if score.size else -1.0
|
||||||
return vi, -1.0
|
|
||||||
best = float(score.max())
|
|
||||||
if pyramid_propagate and best > 0:
|
|
||||||
# Top-K posizioni > top_thresh (max propagate_topk)
|
|
||||||
flat = score.ravel()
|
|
||||||
k = min(propagate_topk, flat.size)
|
|
||||||
idx = np.argpartition(-flat, k - 1)[:k]
|
|
||||||
peaks: list[tuple[int, int, float]] = []
|
|
||||||
for i in idx:
|
|
||||||
s = float(flat[i])
|
|
||||||
if s < top_thresh * 0.7:
|
|
||||||
continue
|
|
||||||
yt, xt = int(i // score.shape[1]), int(i % score.shape[1])
|
|
||||||
peaks.append((xt, yt, s))
|
|
||||||
peaks_by_vi[vi] = peaks
|
|
||||||
return vi, best
|
|
||||||
|
|
||||||
kept_coarse: list[tuple[int, float]] = []
|
kept_coarse: list[tuple[int, float]] = []
|
||||||
all_top_scores: list[tuple[int, float]] = []
|
all_top_scores: list[tuple[int, float]] = []
|
||||||
if self.n_threads > 1 and len(coarse_idx_list) > 1:
|
# batch_top: usa kernel batch single-call con prange-esterno su
|
||||||
|
# varianti. Vince su threadpool quando n_vars >> n_threads e quando
|
||||||
|
# H*W top e' piccolo (overhead chiamate JIT > costo kernel).
|
||||||
|
if (batch_top and HAS_NUMBA and len(coarse_idx_list) > 4):
|
||||||
|
dx_l = []; dy_l = []; bn_l = []; vs_l = []
|
||||||
|
for vi in coarse_idx_list:
|
||||||
|
var = self.variants[vi]
|
||||||
|
lvl = var.levels[min(top, len(var.levels) - 1)]
|
||||||
|
dx_l.append(lvl.dx); dy_l.append(lvl.dy); bn_l.append(lvl.bin)
|
||||||
|
vs_l.append(var.scale)
|
||||||
|
scores_arr = _jit_top_max_per_variant(
|
||||||
|
spread_top, dx_l, dy_l, bn_l, bg_cache_top, vs_l,
|
||||||
|
bit_active_top,
|
||||||
|
)
|
||||||
|
for vi, best in zip(coarse_idx_list, scores_arr.tolist()):
|
||||||
|
all_top_scores.append((vi, best))
|
||||||
|
if best >= top_thresh:
|
||||||
|
kept_coarse.append((vi, best))
|
||||||
|
elif self.n_threads > 1 and len(coarse_idx_list) > 1:
|
||||||
with ThreadPoolExecutor(max_workers=self.n_threads) as ex:
|
with ThreadPoolExecutor(max_workers=self.n_threads) as ex:
|
||||||
for vi, best in ex.map(_top_score, coarse_idx_list):
|
for vi, best in ex.map(_top_score, coarse_idx_list):
|
||||||
all_top_scores.append((vi, best))
|
all_top_scores.append((vi, best))
|
||||||
@@ -736,48 +733,14 @@ class LineShapeMatcher:
|
|||||||
for sc in unique_scales:
|
for sc in unique_scales:
|
||||||
bg_cache_full[sc] = _bg_for_scale(density_full, sc, 1)
|
bg_cache_full[sc] = _bg_for_scale(density_full, sc, 1)
|
||||||
|
|
||||||
# Margine in full-res attorno ad ogni peak top: copre incertezza
|
|
||||||
# downsampling (sf_top px) + spread_radius + slack per NMS.
|
|
||||||
propagate_margin = sf_top + self.spread_radius + max(8, nms_radius // 2)
|
|
||||||
H_full, W_full = spread0.shape
|
|
||||||
|
|
||||||
def _full_score(vi: int) -> tuple[int, np.ndarray]:
|
def _full_score(vi: int) -> tuple[int, np.ndarray]:
|
||||||
var = self.variants[vi]
|
var = self.variants[vi]
|
||||||
lvl0 = var.levels[0]
|
lvl0 = var.levels[0]
|
||||||
if not pyramid_propagate or vi not in peaks_by_vi or not peaks_by_vi[vi]:
|
score = _jit_score_bitmap_rescored(
|
||||||
# Path legacy: scansiona intera scena
|
spread0, lvl0.dx, lvl0.dy, lvl0.bin, bit_active_full,
|
||||||
return vi, _jit_score_bitmap_rescored(
|
bg_cache_full[var.scale],
|
||||||
spread0, lvl0.dx, lvl0.dy, lvl0.bin, bit_active_full,
|
)
|
||||||
bg_cache_full[var.scale],
|
return vi, score
|
||||||
)
|
|
||||||
# Path piramide propagata: valuta solo crop locali attorno
|
|
||||||
# alle posizioni dei picchi top-level (riproiettati a full-res).
|
|
||||||
score_full = np.zeros((H_full, W_full), dtype=np.float32)
|
|
||||||
mark = np.zeros((H_full, W_full), dtype=bool)
|
|
||||||
bg = bg_cache_full[var.scale]
|
|
||||||
for xt, yt, _s in peaks_by_vi[vi]:
|
|
||||||
cx0 = xt * sf_top
|
|
||||||
cy0 = yt * sf_top
|
|
||||||
x_lo = max(0, cx0 - propagate_margin)
|
|
||||||
x_hi = min(W_full, cx0 + propagate_margin + 1)
|
|
||||||
y_lo = max(0, cy0 - propagate_margin)
|
|
||||||
y_hi = min(H_full, cy0 + propagate_margin + 1)
|
|
||||||
if x_hi <= x_lo or y_hi <= y_lo:
|
|
||||||
continue
|
|
||||||
if mark[y_lo:y_hi, x_lo:x_hi].all():
|
|
||||||
continue
|
|
||||||
# Crop spread + bg, valuta kernel sul crop
|
|
||||||
spread_crop = np.ascontiguousarray(spread0[y_lo:y_hi, x_lo:x_hi])
|
|
||||||
bg_crop = np.ascontiguousarray(bg[y_lo:y_hi, x_lo:x_hi])
|
|
||||||
score_crop = _jit_score_bitmap_rescored(
|
|
||||||
spread_crop, lvl0.dx, lvl0.dy, lvl0.bin,
|
|
||||||
bit_active_full, bg_crop,
|
|
||||||
)
|
|
||||||
score_full[y_lo:y_hi, x_lo:x_hi] = np.maximum(
|
|
||||||
score_full[y_lo:y_hi, x_lo:x_hi], score_crop,
|
|
||||||
)
|
|
||||||
mark[y_lo:y_hi, x_lo:x_hi] = True
|
|
||||||
return vi, score_full
|
|
||||||
|
|
||||||
candidates_per_var: list[tuple[int, np.ndarray]] = []
|
candidates_per_var: list[tuple[int, np.ndarray]] = []
|
||||||
raw: list[tuple[float, int, int, int]] = []
|
raw: list[tuple[float, int, int, int]] = []
|
||||||
|
|||||||
Reference in New Issue
Block a user