calibrate
This commit is contained in:
@@ -0,0 +1,643 @@
|
||||
"""Калибровка параметров сравнения по двум пачкам фото (docs/08 §8.4, шаг 3).
|
||||
|
||||
Позитивы — фото одного объекта с разных ракурсов (они же кандидаты в эталоны),
|
||||
негативы — фото других, похожих объектов. Подбираются ТОЛЬКИ параметры
|
||||
сравнения (geometry_model, lowe_ratio, ransac_reproj_threshold и пороги
|
||||
вердикта) — пересчёт эталонов не нужен (docs/04 §4.5.1). Потребители:
|
||||
CvService.calibrate (эндпоинт /api/v1/calibrate) и tools/calibrate.py (CLI).
|
||||
|
||||
Схема:
|
||||
1) extract по каждому фото выполняет потребитель (боевой пайплайн);
|
||||
2) пары «проба–эталон»: эталоны — только позитивы, пробы — позитивы
|
||||
и негативы (боевой сценарий /verify);
|
||||
3) knn-сопоставление считается один раз на пару, далее комбинации
|
||||
lowe/geometry/ransac дёшевы (фильтрация + RANSAC по ≤нескольким сотням пар);
|
||||
4) пороги вердикта подбираются аналитически по наблюдённым метрикам пар —
|
||||
перебор порогов бесплатен, пересчитывать пары не нужно;
|
||||
5) победитель перепроверяется боевым compare_features (защита от расхождения
|
||||
быстрого пути с реальным пайплайном).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from app.config import Config
|
||||
from app.cv.comparison import (
|
||||
MIN_GOOD_MATCHES,
|
||||
VERDICT_MATCH,
|
||||
VERDICT_NO_MATCH,
|
||||
VERDICT_UNCERTAIN,
|
||||
_coverage,
|
||||
_ransac_inliers,
|
||||
compare_features,
|
||||
)
|
||||
from app.cv.exceptions import CalibrationDatasetInvalid
|
||||
from app.cv.extraction import Features
|
||||
from app.cv.params import (
|
||||
_SETTINGS_LIMITS,
|
||||
base_comparison,
|
||||
base_extraction,
|
||||
parse_settings,
|
||||
)
|
||||
|
||||
# Число потоков пула knn-сопоставлений (самая тяжёлая стадия; OpenCV
|
||||
# освобождает GIL). RANSAC выполняется последовательно в вызывающем потоке:
|
||||
# cv2.setRNGSeed — глобальное состояние, параллельные вызовы ломали бы
|
||||
# детерминизм (NFR-009).
|
||||
KNN_POOL_SIZE = 4
|
||||
|
||||
# Сетка перебора — константа процедуры калибровки (аналог формульных констант
|
||||
# comparison.py), а не конфигурируемый параметр: в env-таблице 07.4 её нет.
|
||||
DEFAULT_GRID_GEOMETRY = ("homography", "fundamental")
|
||||
DEFAULT_GRID_LOWE = (0.70, 0.75, 0.80)
|
||||
DEFAULT_GRID_RANSAC = (3.0, 5.0, 8.0)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CalibrationPhoto:
|
||||
"""Загруженное фото пачки; дескрипторы конвертированы в float32 один раз."""
|
||||
|
||||
name: str # отображаемое имя (уникализируется)
|
||||
group: str # "positive" | "negative"
|
||||
index: int # индекс в общем списке фото
|
||||
features: Features
|
||||
descriptors32: np.ndarray
|
||||
|
||||
|
||||
@dataclass
|
||||
class PairKnn:
|
||||
"""knn-матчи одной упорядоченной пары «проба–эталон» (row[0]/row[1])."""
|
||||
|
||||
probe_index: int
|
||||
ref_index: int
|
||||
is_positive: bool
|
||||
qidx: np.ndarray # int32 (K,) — индексы keypoints пробы
|
||||
tidx: np.ndarray # int32 (K,) — индексы keypoints эталона
|
||||
d0: np.ndarray # float32 (K,) — расстояние лучшего
|
||||
d1: np.ndarray # float32 (K,) — расстояние второго
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Grid:
|
||||
geometry_models: tuple[str, ...] = DEFAULT_GRID_GEOMETRY
|
||||
lowe_ratios: tuple[float, ...] = DEFAULT_GRID_LOWE
|
||||
ransac_thresholds: tuple[float, ...] = DEFAULT_GRID_RANSAC
|
||||
|
||||
|
||||
@dataclass
|
||||
class PairRow:
|
||||
probe: str
|
||||
ref: str
|
||||
is_positive: bool
|
||||
good_matches: int
|
||||
inliers: int
|
||||
inlier_ratio: float
|
||||
coverage: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class Selection:
|
||||
match_inliers_min: int
|
||||
match_inliers_ratio_min: float
|
||||
match_coverage_min: float
|
||||
uncertain_inliers_min: int
|
||||
tp: int
|
||||
fp: int
|
||||
fn: int
|
||||
f1: float
|
||||
uncertain_rate: float
|
||||
margin: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class ComboResult:
|
||||
geometry_model: str
|
||||
lowe_ratio: float
|
||||
ransac_reproj_threshold: float
|
||||
selection: Selection
|
||||
rows: list[PairRow] = dataclasses.field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CalibrationOutcome:
|
||||
grid: Grid
|
||||
extraction: dict
|
||||
photos: list[dict] # name/group/keypoints для отчёта
|
||||
skipped: list[dict]
|
||||
pairs_total: int
|
||||
pairs_positive: int
|
||||
ranking: list[ComboResult] # отсортирован от лучшей к худшей
|
||||
presets: dict # {profile: {"tp": int, "fp": int}}
|
||||
settings: dict # {"comparison": {...}} — для /features и /verify
|
||||
selfcheck: dict
|
||||
warnings: list[str]
|
||||
|
||||
@property
|
||||
def best(self) -> ComboResult:
|
||||
return self.ranking[0]
|
||||
|
||||
def _combo_payload(self, combo: ComboResult) -> dict:
|
||||
"""Пороги — в терминах details.thresholds /verify (ThresholdsModel):
|
||||
имена отображения, а не имена ключей запроса settings."""
|
||||
s = combo.selection
|
||||
return {
|
||||
"geometry_model": combo.geometry_model,
|
||||
"lowe_ratio": combo.lowe_ratio,
|
||||
"ransac_reproj_threshold": combo.ransac_reproj_threshold,
|
||||
"thresholds": {
|
||||
"inliers_match": s.match_inliers_min,
|
||||
"inlier_ratio_match": s.match_inliers_ratio_min,
|
||||
"coverage_min": s.match_coverage_min,
|
||||
"inliers_uncertain_min": s.uncertain_inliers_min,
|
||||
},
|
||||
"tp": s.tp,
|
||||
"fp": s.fp,
|
||||
"fn": s.fn,
|
||||
"f1": round(s.f1, 4),
|
||||
"uncertain_rate": round(s.uncertain_rate, 4),
|
||||
"margin": round(s.margin, 4),
|
||||
}
|
||||
|
||||
def payload(self) -> dict:
|
||||
"""Форма ответа POST /api/v1/calibrate (docs/05 §5.4.5)."""
|
||||
best = self.best
|
||||
return {
|
||||
"settings": self.settings,
|
||||
"metrics": {
|
||||
"f1": round(best.selection.f1, 4),
|
||||
"true_matches": best.selection.tp,
|
||||
"false_matches": best.selection.fp,
|
||||
"uncertain_rate": round(best.selection.uncertain_rate, 4),
|
||||
"margin": round(best.selection.margin, 4),
|
||||
"positive_pairs": self.pairs_positive,
|
||||
"negative_pairs": self.pairs_total - self.pairs_positive,
|
||||
},
|
||||
"best": self._combo_payload(best),
|
||||
"ranking": [self._combo_payload(c) for c in self.ranking],
|
||||
"pairs": [
|
||||
{
|
||||
"probe": r.probe,
|
||||
"ref": r.ref,
|
||||
"is_positive": r.is_positive,
|
||||
"good_matches": r.good_matches,
|
||||
"inliers": r.inliers,
|
||||
"inlier_ratio": round(r.inlier_ratio, 4),
|
||||
"coverage": round(r.coverage, 4),
|
||||
"verdict": verdict_of(r, best.selection),
|
||||
}
|
||||
for r in best.rows
|
||||
],
|
||||
"presets": self.presets,
|
||||
"images": self.photos,
|
||||
"skipped": self.skipped,
|
||||
"warnings": self.warnings,
|
||||
"selfcheck": self.selfcheck,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- быстрый путь метрик
|
||||
|
||||
def _knn_pair(probe: CalibrationPhoto, ref: CalibrationPhoto) -> PairKnn | None:
|
||||
"""knnMatch(k=2) — как в compare_features; None при <2 дескрипторов."""
|
||||
if probe.features.count < 2 or ref.features.count < 2:
|
||||
return None
|
||||
matcher = cv2.BFMatcher(normType=cv2.NORM_L2, crossCheck=False)
|
||||
matches = matcher.knnMatch(probe.descriptors32, ref.descriptors32, k=2)
|
||||
rows = [row for row in matches if len(row) == 2]
|
||||
return PairKnn(
|
||||
probe_index=probe.index,
|
||||
ref_index=ref.index,
|
||||
is_positive=probe.group == "positive",
|
||||
qidx=np.array([row[0].queryIdx for row in rows], dtype=np.int32),
|
||||
tidx=np.array([row[0].trainIdx for row in rows], dtype=np.int32),
|
||||
d0=np.array([row[0].distance for row in rows], dtype=np.float32),
|
||||
d1=np.array([row[1].distance for row in rows], dtype=np.float32),
|
||||
)
|
||||
|
||||
|
||||
def _pair_row(
|
||||
knn: PairKnn | None,
|
||||
probe: CalibrationPhoto,
|
||||
ref: CalibrationPhoto,
|
||||
lowe: float,
|
||||
geometry: str,
|
||||
ransac_thr: float,
|
||||
base_params,
|
||||
) -> PairRow:
|
||||
"""Метрики пары для комбинации pipeline-параметров — зеркало compare_features
|
||||
(тот же тест Лоу, тот же RANSAC через _ransac_inliers, та же coverage)."""
|
||||
is_positive = probe.group == "positive"
|
||||
if knn is None:
|
||||
return PairRow(probe.name, ref.name, is_positive, 0, 0, 0.0, 0.0)
|
||||
keep = knn.d0 < lowe * knn.d1
|
||||
good = int(keep.sum())
|
||||
if good < MIN_GOOD_MATCHES:
|
||||
return PairRow(probe.name, ref.name, is_positive, good, 0, 0.0, 0.0)
|
||||
probe_pts = probe.features.keypoints[knn.qidx[keep], :2]
|
||||
ref_pts = ref.features.keypoints[knn.tidx[keep], :2]
|
||||
params = dataclasses.replace(
|
||||
base_params,
|
||||
geometry_model=geometry,
|
||||
lowe_ratio=lowe,
|
||||
ransac_reproj_threshold=ransac_thr,
|
||||
)
|
||||
mask = _ransac_inliers(ref_pts, probe_pts, params)
|
||||
if mask is None or mask.size == 0:
|
||||
return PairRow(probe.name, ref.name, is_positive, good, 0, 0.0, 0.0)
|
||||
inliers = int(np.count_nonzero(mask))
|
||||
return PairRow(
|
||||
probe=probe.name,
|
||||
ref=ref.name,
|
||||
is_positive=is_positive,
|
||||
good_matches=good,
|
||||
inliers=inliers,
|
||||
inlier_ratio=inliers / good,
|
||||
coverage=_coverage(probe_pts, mask, probe.features),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- подбор порогов
|
||||
|
||||
def _threshold_candidates(values: np.ndarray, lo: float, hi: float, is_int: bool,
|
||||
max_candidates: int = 33) -> np.ndarray:
|
||||
"""Кандидаты порога: середины между соседними наблюдёнными значениями
|
||||
плюс границы диапазона (чтобы можно было «пропустить всё» / «пропустить
|
||||
ничего» по измерению). Для целых — округление вверх: условие inliers ≥ t."""
|
||||
uniq = np.unique(values)
|
||||
if uniq.size == 0:
|
||||
uniq = np.array([lo])
|
||||
mids = (uniq[:-1] + uniq[1:]) / 2 if uniq.size > 1 else np.array([])
|
||||
cands = np.concatenate(([lo], mids, [hi]))
|
||||
cands = np.clip(cands, lo, hi)
|
||||
if is_int:
|
||||
cands = np.unique(np.ceil(cands).astype(np.int64))
|
||||
else:
|
||||
cands = np.unique(cands)
|
||||
if cands.size > max_candidates:
|
||||
idx = np.unique(np.linspace(0, cands.size - 1, max_candidates).astype(int))
|
||||
cands = cands[idx]
|
||||
return cands
|
||||
|
||||
|
||||
def _separation_margin(
|
||||
tp_inl, tp_rat, tp_cov, neg_inl, neg_rat, neg_cov,
|
||||
all_inl, all_rat, all_cov,
|
||||
) -> float:
|
||||
"""Нормированный зазор между худшей проходящей позитивной парой и лучшим
|
||||
негативом по самому узкому измерению (чем больше — тем устойчивее пороги)."""
|
||||
if len(tp_inl) == 0 or len(neg_inl) == 0:
|
||||
return 0.0
|
||||
|
||||
def dim(tp, neg, allv):
|
||||
spread = float(allv.max() - allv.min())
|
||||
if spread <= 0:
|
||||
return 0.0
|
||||
return (float(tp.min()) - float(neg.max())) / spread
|
||||
|
||||
return min(
|
||||
dim(tp_inl, neg_inl, all_inl),
|
||||
dim(tp_rat, neg_rat, all_rat),
|
||||
dim(tp_cov, neg_cov, all_cov),
|
||||
)
|
||||
|
||||
|
||||
def _dim_centeredness(values: np.ndarray, thr: float, pass_bool: np.ndarray) -> float:
|
||||
"""Устойчивость порога одного измерения: насколько он «в центре» зазора
|
||||
между проходящими и непроходящими наблюдёнными значениями (0.5 — ровно
|
||||
посередине; ближе к данным — меньше). Измерение, которое ничего не
|
||||
отсекает, оценивается отступом порога от ближайшего значения данных;
|
||||
вырожденное (все значения равны) — 0.5."""
|
||||
if not pass_bool.any():
|
||||
return 0.0
|
||||
a = float(values[pass_bool].min())
|
||||
fail = ~pass_bool
|
||||
if fail.any():
|
||||
b = float(values[fail].max())
|
||||
if a <= b:
|
||||
return 0.0
|
||||
return min(a - thr, thr - b) / (a - b)
|
||||
spread = float(values.max() - values.min())
|
||||
if spread <= 0:
|
||||
return 0.5
|
||||
return float(min(0.5, (a - thr) / spread))
|
||||
|
||||
|
||||
def derive_uncertain_min(neg_inliers: np.ndarray, match_inliers_min: int) -> int:
|
||||
"""Негативы должны попадать в no_match, а не в uncertain: граница зоны
|
||||
ручной проверки — сразу над худшим негативом (в рамках допустимого
|
||||
uncertain ≤ match, иначе конфиг невалиден)."""
|
||||
max_neg = int(neg_inliers.max()) if neg_inliers.size else 0
|
||||
return int(min(max(1, max_neg + 1), match_inliers_min))
|
||||
|
||||
|
||||
def select_thresholds(rows: list[PairRow]) -> Selection:
|
||||
"""Аналитический перебор порогов вердикта по наблюдённым метрикам пар.
|
||||
|
||||
Ранжирование: F1 класса match (docs/08 §8.4), затем минимум ложных match,
|
||||
затем максимум true positives, затем центрированность порогов в зазорах
|
||||
между классами (устойчивость к дрейфу данных); при равной центрированности
|
||||
— более строгие пороги (консервативность). `margin` — итоговый
|
||||
нормированный зазор между классами, возвращается для отчёта.
|
||||
"""
|
||||
inl = np.array([r.inliers for r in rows], dtype=np.float64)
|
||||
rat = np.array([r.inlier_ratio for r in rows], dtype=np.float64)
|
||||
cov = np.array([r.coverage for r in rows], dtype=np.float64)
|
||||
pos = np.array([r.is_positive for r in rows], dtype=bool)
|
||||
n_pos = int(pos.sum())
|
||||
|
||||
ci = _threshold_candidates(inl, *_SETTINGS_LIMITS["match_inliers_min"][1:], is_int=True)
|
||||
cr = _threshold_candidates(rat, *_SETTINGS_LIMITS["match_inliers_ratio_min"][1:], is_int=False)
|
||||
cc = _threshold_candidates(cov, *_SETTINGS_LIMITS["match_coverage_min"][1:], is_int=False)
|
||||
|
||||
pass_i = inl[:, None] >= ci[None, :]
|
||||
pass_r = rat[:, None] >= cr[None, :]
|
||||
pass_c = cov[:, None] >= cc[None, :]
|
||||
|
||||
# match = все три условия; считаем tp/fp по срезам третьего измерения,
|
||||
# чтобы не материализовать (n, Ci, Cr, Cc)
|
||||
tp = np.zeros((ci.size, cr.size, cc.size), dtype=np.int64)
|
||||
fp = np.zeros_like(tp)
|
||||
for k in range(cc.size):
|
||||
m = pass_i[:, :, None] & pass_r[:, None, :] & pass_c[:, k][:, None, None]
|
||||
tp[:, :, k] = np.where(pos[:, None, None], m, False).sum(axis=0)
|
||||
fp[:, :, k] = np.where(~pos[:, None, None], m, False).sum(axis=0)
|
||||
fn = n_pos - tp
|
||||
|
||||
denom = 2 * tp + fp + fn
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
f1 = np.where(denom > 0, 2 * tp / np.maximum(denom, 1), 0.0)
|
||||
|
||||
best_f1 = f1.max()
|
||||
f1_mask = f1 == best_f1
|
||||
fp_at = int(fp[f1_mask].min())
|
||||
tp_at = int(tp[f1_mask & (fp == fp_at)].max())
|
||||
tied = np.argwhere(f1_mask & (fp == fp_at) & (tp == tp_at))
|
||||
|
||||
def _norm(t: float, arr: np.ndarray) -> float:
|
||||
span = float(arr[-1] - arr[0])
|
||||
return (float(t) - float(arr[0])) / span if span > 0 else 0.0
|
||||
|
||||
best_cell, best_key = (int(tied[0][0]), int(tied[0][1]), int(tied[0][2])), (-1.0, -1.0)
|
||||
for i, j, k in tied:
|
||||
score = round(min(
|
||||
_dim_centeredness(inl, ci[i], pass_i[:, i]),
|
||||
_dim_centeredness(rat, cr[j], pass_r[:, j]),
|
||||
_dim_centeredness(cov, cc[k], pass_c[:, k]),
|
||||
), 9) # округление — не давать шуму float решать исход сравнения
|
||||
key = (score, _norm(ci[i], ci) + _norm(cr[j], cr) + _norm(cc[k], cc))
|
||||
if key > best_key:
|
||||
best_cell, best_key = (int(i), int(j), int(k)), key
|
||||
|
||||
i, j, k = best_cell
|
||||
ti, tr, tc = int(ci[i]), round(float(cr[j]), 4), round(float(cc[k]), 4)
|
||||
# после округления пересчитываем итоги по тем же строкам — в settings
|
||||
# попадают значения, которыми реально классифицировали
|
||||
match_mask = (inl >= ti) & (rat >= tr) & (cov >= tc)
|
||||
neg_mask = ~pos
|
||||
tp_v, fp_v = int((match_mask & pos).sum()), int((match_mask & neg_mask).sum())
|
||||
unc = derive_uncertain_min(inl[neg_mask], ti)
|
||||
uncertain = int(np.count_nonzero((inl >= unc) & ~match_mask))
|
||||
margin = _separation_margin(
|
||||
inl[match_mask & pos], rat[match_mask & pos], cov[match_mask & pos],
|
||||
inl[neg_mask], rat[neg_mask], cov[neg_mask],
|
||||
inl, rat, cov,
|
||||
)
|
||||
return Selection(
|
||||
match_inliers_min=ti,
|
||||
match_inliers_ratio_min=tr,
|
||||
match_coverage_min=tc,
|
||||
uncertain_inliers_min=unc,
|
||||
tp=tp_v,
|
||||
fp=fp_v,
|
||||
fn=n_pos - tp_v,
|
||||
f1=float(best_f1),
|
||||
uncertain_rate=uncertain / len(rows),
|
||||
margin=float(margin),
|
||||
)
|
||||
|
||||
|
||||
def verdict_of(row: PairRow, sel: Selection) -> str:
|
||||
if (
|
||||
row.inliers >= sel.match_inliers_min
|
||||
and row.inlier_ratio >= sel.match_inliers_ratio_min
|
||||
and row.coverage >= sel.match_coverage_min
|
||||
):
|
||||
return VERDICT_MATCH
|
||||
if row.inliers >= sel.uncertain_inliers_min:
|
||||
return VERDICT_UNCERTAIN
|
||||
return VERDICT_NO_MATCH
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- оркестрация
|
||||
|
||||
def _preset_thresholds(config: Config) -> dict[str, tuple[int, float, float]]:
|
||||
"""Пороги стандартных профилей (facade/monument/repetitive) — базовые
|
||||
значения с наложением пресета; для сравнения с подобранными."""
|
||||
from app.cv.params import PROFILES
|
||||
|
||||
base = base_comparison(config)
|
||||
result = {}
|
||||
for name, preset in PROFILES.items():
|
||||
comp = {**dataclasses.asdict(base), **preset["comparison"]}
|
||||
result[name] = (
|
||||
comp["match_inliers_min"],
|
||||
comp["match_inliers_ratio_min"],
|
||||
comp["match_coverage_min"],
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _preset_counts(rows: list[PairRow], thresholds: tuple[int, float, float]) -> tuple[int, int]:
|
||||
ti, tr, tc = thresholds
|
||||
tp = sum(
|
||||
1 for r in rows
|
||||
if r.is_positive and r.inliers >= ti and r.inlier_ratio >= tr and r.coverage >= tc
|
||||
)
|
||||
fp = sum(
|
||||
1 for r in rows
|
||||
if not r.is_positive and r.inliers >= ti and r.inlier_ratio >= tr and r.coverage >= tc
|
||||
)
|
||||
return tp, fp
|
||||
|
||||
|
||||
def _unique_names(photos: list[CalibrationPhoto]) -> None:
|
||||
"""Одинаковые имена файлов в двух пачках не должны склеиваться в отчётах."""
|
||||
seen: dict[str, int] = {}
|
||||
for photo in photos:
|
||||
base = photo.name
|
||||
count = seen.get(base, 0)
|
||||
seen[base] = count + 1
|
||||
if count:
|
||||
photo.name = f"{base} [{count}]"
|
||||
|
||||
|
||||
def _warnings(sel: Selection, best_rows: list[PairRow], pairs_total: int) -> list[str]:
|
||||
warnings: list[str] = []
|
||||
fp_rows = [r for r in best_rows if not r.is_positive and verdict_of(r, sel) == VERDICT_MATCH]
|
||||
if fp_rows:
|
||||
warnings.append(
|
||||
"Есть ложные match на негативах ("
|
||||
+ ", ".join(f"{r.probe}→{r.ref}" for r in fp_rows)
|
||||
+ ") — добавьте похожих негативов"
|
||||
)
|
||||
bad_pos = [r for r in best_rows if r.is_positive and verdict_of(r, sel) != VERDICT_MATCH]
|
||||
if bad_pos:
|
||||
warnings.append(
|
||||
"Позитивные пары без match ("
|
||||
+ ", ".join(f"{r.probe}→{r.ref}" for r in bad_pos)
|
||||
+ ") — добавьте ракурсов"
|
||||
)
|
||||
if pairs_total < 20:
|
||||
warnings.append("Пар мало (<20) — статистика неустойчива, добавьте фото в оба набора")
|
||||
return warnings
|
||||
|
||||
|
||||
def run_calibration(
|
||||
positives: list[CalibrationPhoto],
|
||||
negatives: list[CalibrationPhoto],
|
||||
skipped: list[dict],
|
||||
config: Config,
|
||||
grid: Grid | None = None,
|
||||
jobs: int | None = None,
|
||||
) -> CalibrationOutcome:
|
||||
"""Полный прогон по уже извлечённым фото. Минимумы проверяет вызывающий
|
||||
(или получается CalibrationDatasetInvalid отсюда — после отбраковки)."""
|
||||
if len(positives) < 2:
|
||||
raise CalibrationDatasetInvalid(
|
||||
f"Нужно ≥ 2 валидных позитивных фото (загружено {len(positives)}), "
|
||||
"иначе нет ни одной позитивной пары"
|
||||
)
|
||||
if not negatives:
|
||||
raise CalibrationDatasetInvalid(
|
||||
"Нужен ≥ 1 валидный негатив (фото похожего объекта) — иначе "
|
||||
"калибруется только полнота, а ложные срабатывания не оцениваются"
|
||||
)
|
||||
|
||||
grid = grid or Grid()
|
||||
base_comp = base_comparison(config)
|
||||
extraction_payload = base_extraction(config).fingerprint_payload()
|
||||
|
||||
photos = positives + negatives
|
||||
for idx, photo in enumerate(photos):
|
||||
photo.index = idx
|
||||
_unique_names(photos)
|
||||
|
||||
# Эталоны — позитивы; пробы — все фото. Упорядоченные пары индексов без самосравнений.
|
||||
positive_indices = [p.index for p in positives]
|
||||
pair_defs = [
|
||||
(probe_idx, ref_idx)
|
||||
for probe_idx in range(len(photos))
|
||||
for ref_idx in positive_indices
|
||||
if probe_idx != ref_idx
|
||||
]
|
||||
by_index = {p.index: p for p in photos}
|
||||
workers = jobs or KNN_POOL_SIZE
|
||||
if len(pair_defs) == 1:
|
||||
knns = [_knn_pair(by_index[pair_defs[0][0]], by_index[pair_defs[0][1]])]
|
||||
else:
|
||||
with ThreadPoolExecutor(max_workers=min(workers, len(pair_defs))) as pool:
|
||||
knns = list(
|
||||
pool.map(lambda pr: _knn_pair(by_index[pr[0]], by_index[pr[1]]), pair_defs)
|
||||
)
|
||||
knn_by_pair = {
|
||||
knn.probe_index * len(photos) + knn.ref_index: knn for knn in knns if knn is not None
|
||||
}
|
||||
|
||||
combos: list[ComboResult] = []
|
||||
for geometry in grid.geometry_models:
|
||||
for lowe in grid.lowe_ratios:
|
||||
for ransac in grid.ransac_thresholds:
|
||||
rows = [
|
||||
_pair_row(
|
||||
knn_by_pair.get(probe_idx * len(photos) + ref_idx),
|
||||
by_index[probe_idx], by_index[ref_idx], lowe, geometry, ransac, base_comp,
|
||||
)
|
||||
for probe_idx, ref_idx in pair_defs
|
||||
]
|
||||
combos.append(ComboResult(
|
||||
geometry_model=geometry,
|
||||
lowe_ratio=lowe,
|
||||
ransac_reproj_threshold=ransac,
|
||||
selection=select_thresholds(rows),
|
||||
rows=rows,
|
||||
))
|
||||
combos.sort(
|
||||
key=lambda c: (
|
||||
-c.selection.f1,
|
||||
c.selection.fp,
|
||||
-c.selection.tp,
|
||||
c.selection.uncertain_rate,
|
||||
-c.selection.margin,
|
||||
)
|
||||
)
|
||||
best = combos[0]
|
||||
sel = best.selection
|
||||
|
||||
# Контроль: боевой compare_features должен воспроизвести вердикты быстрого пути.
|
||||
winner_params = dataclasses.replace(
|
||||
base_comp,
|
||||
geometry_model=best.geometry_model,
|
||||
lowe_ratio=best.lowe_ratio,
|
||||
ransac_reproj_threshold=best.ransac_reproj_threshold,
|
||||
match_inliers_min=sel.match_inliers_min,
|
||||
match_inliers_ratio_min=sel.match_inliers_ratio_min,
|
||||
match_coverage_min=sel.match_coverage_min,
|
||||
uncertain_inliers_min=sel.uncertain_inliers_min,
|
||||
)
|
||||
selfcheck_total = selfcheck_ok = 0
|
||||
mismatches: list[dict] = []
|
||||
by_name = {p.name: p for p in photos}
|
||||
for row in best.rows:
|
||||
real = compare_features(
|
||||
by_name[row.probe].features, by_name[row.ref].features, winner_params
|
||||
)
|
||||
selfcheck_total += 1
|
||||
if real.verdict == verdict_of(row, sel):
|
||||
selfcheck_ok += 1
|
||||
else:
|
||||
mismatches.append({
|
||||
"probe": row.probe, "ref": row.ref,
|
||||
"expected": verdict_of(row, sel), "real": real.verdict,
|
||||
})
|
||||
|
||||
settings = {
|
||||
"comparison": {
|
||||
"geometry_model": best.geometry_model,
|
||||
"lowe_ratio": best.lowe_ratio,
|
||||
"ransac_reproj_threshold": best.ransac_reproj_threshold,
|
||||
"match_inliers_min": sel.match_inliers_min,
|
||||
"match_inliers_ratio_min": sel.match_inliers_ratio_min,
|
||||
"match_coverage_min": sel.match_coverage_min,
|
||||
"uncertain_inliers_min": sel.uncertain_inliers_min,
|
||||
}
|
||||
}
|
||||
# Гарантия, что сервис примет выданные настройки (FR-008: строгая валидация).
|
||||
parse_settings(settings, config)
|
||||
|
||||
presets = {
|
||||
name: dict(zip(("tp", "fp"), _preset_counts(best.rows, thr)))
|
||||
for name, thr in _preset_thresholds(config).items()
|
||||
}
|
||||
pairs_positive = sum(1 for probe, _ in pair_defs if by_index[probe].group == "positive")
|
||||
|
||||
return CalibrationOutcome(
|
||||
grid=grid,
|
||||
extraction=extraction_payload,
|
||||
photos=[
|
||||
{"name": p.name, "group": p.group, "keypoints": p.features.count}
|
||||
for p in photos
|
||||
],
|
||||
skipped=skipped,
|
||||
pairs_total=len(pair_defs),
|
||||
pairs_positive=pairs_positive,
|
||||
ranking=combos,
|
||||
presets=presets,
|
||||
settings=settings,
|
||||
selfcheck={"checked": selfcheck_total, "matched": selfcheck_ok, "mismatches": mismatches},
|
||||
warnings=_warnings(sel, best.rows, len(pair_defs)),
|
||||
)
|
||||
Reference in New Issue
Block a user