Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6db2086ead |
+72
-36
@@ -239,8 +239,6 @@ class LineShapeMatcher:
|
|||||||
self._train_mask = mask_full.copy()
|
self._train_mask = mask_full.copy()
|
||||||
|
|
||||||
self.variants.clear()
|
self.variants.clear()
|
||||||
# Invalida cache feature di refine: il template e cambiato.
|
|
||||||
self._refine_feat_cache = {}
|
|
||||||
for s in self._scale_list():
|
for s in self._scale_list():
|
||||||
sw = max(16, int(round(w * s)))
|
sw = max(16, int(round(w * s)))
|
||||||
sh = max(16, int(round(h * s)))
|
sh = max(16, int(round(h * s)))
|
||||||
@@ -435,36 +433,17 @@ class LineShapeMatcher:
|
|||||||
H, W = spread0.shape
|
H, W = spread0.shape
|
||||||
margin = 3
|
margin = 3
|
||||||
|
|
||||||
# Cache template features per angolo (chiave: int(round(ang*20)) =
|
|
||||||
# bucket di 0.05°). Golden-search ricontratto puo richiedere lo
|
|
||||||
# stesso bucket piu volte; evita re-warp+gradient+extract (costoso).
|
|
||||||
# Cache a livello matcher per riusare tra chiamate find() su scene
|
|
||||||
# diverse: la rotazione del template non dipende dalla scena.
|
|
||||||
if not hasattr(self, '_refine_feat_cache'):
|
|
||||||
self._refine_feat_cache = {}
|
|
||||||
feat_cache = self._refine_feat_cache
|
|
||||||
cache_scale_key = round(scale * 1000)
|
|
||||||
|
|
||||||
def _score_at_angle(off: float) -> tuple[float, float, float]:
|
def _score_at_angle(off: float) -> tuple[float, float, float]:
|
||||||
"""Ritorna (score, best_cx, best_cy) per angolo = angle_deg + off."""
|
"""Ritorna (score, best_cx, best_cy) per angolo = angle_deg + off."""
|
||||||
ang = angle_deg + off
|
ang = angle_deg + off
|
||||||
ck = (round(ang * 20), cache_scale_key)
|
M = cv2.getRotationMatrix2D(center, ang, 1.0)
|
||||||
cached = feat_cache.get(ck)
|
gray_r = cv2.warpAffine(gray_p, M, (diag, diag),
|
||||||
if cached is not None:
|
flags=cv2.INTER_LINEAR,
|
||||||
fx, fy, fb = cached
|
borderMode=cv2.BORDER_REPLICATE)
|
||||||
else:
|
mask_r = cv2.warpAffine(mask_p, M, (diag, diag),
|
||||||
M = cv2.getRotationMatrix2D(center, ang, 1.0)
|
flags=cv2.INTER_NEAREST, borderValue=0)
|
||||||
gray_r = cv2.warpAffine(gray_p, M, (diag, diag),
|
mag, bins = self._gradient(gray_r)
|
||||||
flags=cv2.INTER_LINEAR,
|
fx, fy, fb = self._extract_features(mag, bins, mask_r)
|
||||||
borderMode=cv2.BORDER_REPLICATE)
|
|
||||||
mask_r = cv2.warpAffine(mask_p, M, (diag, diag),
|
|
||||||
flags=cv2.INTER_NEAREST, borderValue=0)
|
|
||||||
mag, bins = self._gradient(gray_r)
|
|
||||||
fx, fy, fb = self._extract_features(mag, bins, mask_r)
|
|
||||||
# LRU semplice: limita cache a ~256 angoli (8 angoli * 32 candidati)
|
|
||||||
if len(feat_cache) > 256:
|
|
||||||
feat_cache.pop(next(iter(feat_cache)))
|
|
||||||
feat_cache[ck] = (fx, fy, fb)
|
|
||||||
if len(fx) < 8:
|
if len(fx) < 8:
|
||||||
return (0.0, cx, cy)
|
return (0.0, cx, cy)
|
||||||
dx = (fx - center[0]).astype(np.int32)
|
dx = (fx - center[0]).astype(np.int32)
|
||||||
@@ -595,6 +574,8 @@ 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,
|
||||||
|
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:
|
||||||
@@ -666,7 +647,12 @@ 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).
|
||||||
|
# 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)]
|
||||||
@@ -674,7 +660,23 @@ 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],
|
||||||
)
|
)
|
||||||
return vi, float(score.max()) if score.size else -1.0
|
if score.size == 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]] = []
|
||||||
@@ -734,14 +736,48 @@ 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]
|
||||||
score = _jit_score_bitmap_rescored(
|
if not pyramid_propagate or vi not in peaks_by_vi or not peaks_by_vi[vi]:
|
||||||
spread0, lvl0.dx, lvl0.dy, lvl0.bin, bit_active_full,
|
# Path legacy: scansiona intera scena
|
||||||
bg_cache_full[var.scale],
|
return vi, _jit_score_bitmap_rescored(
|
||||||
)
|
spread0, lvl0.dx, lvl0.dy, lvl0.bin, bit_active_full,
|
||||||
return vi, score
|
bg_cache_full[var.scale],
|
||||||
|
)
|
||||||
|
# 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