calibrate
This commit is contained in:
@@ -11,6 +11,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.cv.exceptions import (
|
||||
BlobInvalid,
|
||||
CalibrationDatasetInvalid,
|
||||
CvError,
|
||||
FormatUnsupported,
|
||||
ImageDecodeFailed,
|
||||
@@ -30,6 +31,7 @@ _CV_ERROR_MAP: list[tuple[type[CvError], int, str]] = [
|
||||
(UnknownProfile, 400, "UNKNOWN_PROFILE"),
|
||||
(ImageFormatUnsupported, 415, "UNSUPPORTED_MEDIA_TYPE"),
|
||||
(InvalidSettings, 422, "INVALID_SETTINGS"),
|
||||
(CalibrationDatasetInvalid, 422, "CALIBRATION_DATASET_INVALID"),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from starlette.datastructures import UploadFile
|
||||
from app.api.deps import check_image_content_type, require_api_key
|
||||
from app.api.errors import ApiError
|
||||
from app.api.schemas import (
|
||||
CalibrateResponse,
|
||||
ProfileModel,
|
||||
ProfilesResponse,
|
||||
StatusResponse,
|
||||
@@ -192,6 +193,78 @@ async def verify(request: Request):
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------- /calibrate
|
||||
|
||||
|
||||
async def _read_pack_parts(parts: list, name: str, config) -> list[tuple[str, bytes]]:
|
||||
"""Читает повторяемые файловые части пачки: [(имя файла, байты)]."""
|
||||
payloads: list[tuple[str, bytes]] = []
|
||||
for i, part in enumerate(parts):
|
||||
if isinstance(part, str):
|
||||
raise ApiError(
|
||||
422, "VALIDATION_ERROR",
|
||||
f"Часть {name}[{i}] должна быть файлом",
|
||||
{"part": name, "index": i},
|
||||
)
|
||||
check_image_content_type(part.content_type, f"{name}[{i}]")
|
||||
data = await part.read()
|
||||
_check_image_size(data, f"{name}[{i}]", config.max_image_bytes)
|
||||
payloads.append((part.filename or f"{name}[{i}]", data))
|
||||
return payloads
|
||||
|
||||
|
||||
def _check_pack_size(parts: list, name: str, minimum: int, maximum: int) -> None:
|
||||
if len(parts) < minimum:
|
||||
raise ApiError(
|
||||
422, "VALIDATION_ERROR",
|
||||
f"Частей {name} меньше минимума ({minimum}): калибровка невозможна",
|
||||
{"part": name, "count": len(parts), "minimum": minimum},
|
||||
)
|
||||
if len(parts) > maximum:
|
||||
raise ApiError(
|
||||
400, "TOO_MANY_CALIBRATION_IMAGES",
|
||||
f"Число фото в пачке {name} ({len(parts)}) превышает лимит {maximum}",
|
||||
{"part": name, "count": len(parts), "limit": maximum},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/calibrate", dependencies=[Depends(require_api_key)])
|
||||
async def calibrate(request: Request):
|
||||
"""Подбор per-объектных настроек сравнения по двум пачкам фото
|
||||
(docs/05 §5.4.5): positive — один объект с разных ракурсов, negative —
|
||||
похожие объекты. Тяжёлый запрос: до ~60 с при максимальных пачках."""
|
||||
config = _config(request)
|
||||
form = await request.form()
|
||||
|
||||
positive_raw = form.getlist("positive")
|
||||
negative_raw = form.getlist("negative")
|
||||
limit = config.calibration_max_images_per_pack
|
||||
_check_pack_size(positive_raw, "positive", minimum=2, maximum=limit)
|
||||
_check_pack_size(negative_raw, "negative", minimum=1, maximum=limit)
|
||||
positive_parts = await _read_pack_parts(positive_raw, "positive", config)
|
||||
negative_parts = await _read_pack_parts(negative_raw, "negative", config)
|
||||
|
||||
started = time.perf_counter()
|
||||
outcome = await run_in_threadpool(
|
||||
_service(request).calibrate, positive_parts, negative_parts
|
||||
)
|
||||
processing_ms = int((time.perf_counter() - started) * 1000)
|
||||
|
||||
best = outcome.best
|
||||
log_event(
|
||||
logger, logging.INFO, "calibration completed",
|
||||
trace_id=getattr(request.state, "trace_id", ""),
|
||||
geometry_model=best.geometry_model,
|
||||
lowe_ratio=best.lowe_ratio,
|
||||
f1=round(best.selection.f1, 4),
|
||||
true_matches=best.selection.tp,
|
||||
false_matches=best.selection.fp,
|
||||
pairs=outcome.pairs_total,
|
||||
processing_ms=processing_ms,
|
||||
)
|
||||
return CalibrateResponse(**outcome.payload(), processing_ms=processing_ms)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- /profiles
|
||||
|
||||
|
||||
|
||||
@@ -53,6 +53,66 @@ class ProfilesResponse(BaseModel):
|
||||
defaults: dict = Field(description="Базовые значения (env-умолчания) для наследования")
|
||||
|
||||
|
||||
class CalibrateComboModel(BaseModel):
|
||||
"""Одна комбинация pipeline-параметров с подобранными порогами (docs/05 §5.4.5)."""
|
||||
|
||||
geometry_model: str
|
||||
lowe_ratio: float
|
||||
ransac_reproj_threshold: float
|
||||
thresholds: dict = Field(
|
||||
description="Подобранные пороги вердикта: inliers_match, inlier_ratio_match, "
|
||||
"coverage_min, inliers_uncertain_min"
|
||||
)
|
||||
tp: int = Field(description="Позитивные пары с вердиктом match")
|
||||
fp: int = Field(description="Ложные match на негативных парах")
|
||||
fn: int
|
||||
f1: float
|
||||
uncertain_rate: float
|
||||
margin: float = Field(description="Нормированный зазор между классами (устойчивость)")
|
||||
|
||||
|
||||
class CalibratePairModel(BaseModel):
|
||||
probe: str
|
||||
ref: str
|
||||
is_positive: bool
|
||||
good_matches: int
|
||||
inliers: int
|
||||
inlier_ratio: float
|
||||
coverage: float
|
||||
verdict: Literal["match", "uncertain", "no_match"]
|
||||
|
||||
|
||||
class CalibrateImageModel(BaseModel):
|
||||
name: str
|
||||
group: Literal["positive", "negative"]
|
||||
keypoints: int
|
||||
|
||||
|
||||
class CalibrateSkippedModel(BaseModel):
|
||||
name: str
|
||||
group: str
|
||||
reason: str
|
||||
|
||||
|
||||
class CalibrateResponse(BaseModel):
|
||||
"""Полный отчёт калибровки (docs/05 §5.4.5)."""
|
||||
|
||||
settings: dict = Field(
|
||||
description="Готовый фрагмент settings: передать в /features при регистрации "
|
||||
"эталонов и/или в /verify для этого объекта"
|
||||
)
|
||||
metrics: dict
|
||||
best: CalibrateComboModel
|
||||
ranking: list[CalibrateComboModel] = Field(description="Все комбинации, от лучшей к худшей")
|
||||
pairs: list[CalibratePairModel]
|
||||
presets: dict = Field(description="tp/fp стандартных профилей на тех же данных")
|
||||
images: list[CalibrateImageModel]
|
||||
skipped: list[CalibrateSkippedModel]
|
||||
warnings: list[str]
|
||||
selfcheck: dict
|
||||
processing_ms: int
|
||||
|
||||
|
||||
class StatusResponse(BaseModel):
|
||||
status: str
|
||||
|
||||
|
||||
@@ -61,6 +61,8 @@ class Config:
|
||||
max_image_bytes: int # MAX_IMAGE_MB
|
||||
verify_max_body_bytes: int # VERIFY_MAX_BODY_MB
|
||||
max_references: int # MAX_REFERENCES_PER_REQUEST
|
||||
calibration_max_images_per_pack: int # CALIBRATION_MAX_IMAGES_PER_PACK
|
||||
calibration_max_body_bytes: int # CALIBRATION_MAX_BODY_MB
|
||||
|
||||
sift_max_image_size: int
|
||||
sift_max_keypoints: int
|
||||
@@ -91,6 +93,14 @@ class Config:
|
||||
_read("MAX_REFERENCES_PER_REQUEST", "32"),
|
||||
1, 128,
|
||||
),
|
||||
calibration_max_images_per_pack=_to_int(
|
||||
"CALIBRATION_MAX_IMAGES_PER_PACK",
|
||||
_read("CALIBRATION_MAX_IMAGES_PER_PACK", "8"),
|
||||
2, 32,
|
||||
),
|
||||
calibration_max_body_bytes=_to_int(
|
||||
"CALIBRATION_MAX_BODY_MB", _read("CALIBRATION_MAX_BODY_MB", "64"), 1, 512
|
||||
) * _MB,
|
||||
sift_max_image_size=_to_int(
|
||||
"SIFT_MAX_IMAGE_SIZE", _read("SIFT_MAX_IMAGE_SIZE", "1600"), 320, 8192
|
||||
),
|
||||
@@ -126,5 +136,9 @@ class Config:
|
||||
problems.append(
|
||||
"UNCERTAIN_INLIERS_MIN не может превышать MATCH_INLIERS_MIN"
|
||||
)
|
||||
if self.calibration_max_body_bytes < self.max_image_bytes:
|
||||
problems.append(
|
||||
"CALIBRATION_MAX_BODY_MB не может быть меньше MAX_IMAGE_MB"
|
||||
)
|
||||
if problems:
|
||||
raise ConfigError("; ".join(problems))
|
||||
|
||||
@@ -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)),
|
||||
)
|
||||
@@ -69,3 +69,8 @@ class UnknownProfile(CvError):
|
||||
|
||||
class InvalidSettings(CvError):
|
||||
"""Неизвестный ключ или значение вне диапазона в settings (422 INVALID_SETTINGS)."""
|
||||
|
||||
|
||||
class CalibrationDatasetInvalid(CvError):
|
||||
"""После отбраковки битых файлов осталось <2 позитивов или <1 негатива
|
||||
(422 CALIBRATION_DATASET_INVALID)."""
|
||||
|
||||
+40
-1
@@ -17,8 +17,9 @@ import numpy as np
|
||||
from app.config import Config
|
||||
from app.cv import blob as blob_codec
|
||||
from app.cv import resolver
|
||||
from app.cv.calibration import CalibrationOutcome, CalibrationPhoto, run_calibration
|
||||
from app.cv.comparison import PairMetrics, PairResult, compare_features
|
||||
from app.cv.exceptions import CvError, ImageDecodeFailed
|
||||
from app.cv.exceptions import CalibrationDatasetInvalid, CvError, ImageDecodeFailed
|
||||
from app.cv.extraction import Features, extract
|
||||
from app.cv.params import RequestSettings, parse_settings, validate_stored_settings
|
||||
|
||||
@@ -143,6 +144,44 @@ class CvService:
|
||||
|
||||
# ------------------------------------------------------------- internals
|
||||
|
||||
def calibrate(
|
||||
self,
|
||||
positive_parts: list[tuple[str, bytes]],
|
||||
negative_parts: list[tuple[str, bytes]],
|
||||
) -> CalibrationOutcome:
|
||||
"""Калибровка per-объектных настроек сравнения по двум пачкам фото
|
||||
(docs/08 §8.4; эндпоинт /api/v1/calibrate).
|
||||
|
||||
Битовые файлы пропускаются с записью в skipped; недостаток валидных
|
||||
фото — CalibrationDatasetInvalid. Извлечение — по env-умолчаниям:
|
||||
калибруются только параметры сравнения, пересчёт эталонов не нужен.
|
||||
"""
|
||||
extraction = resolver.effective_extraction(self.config, None)
|
||||
positives, skipped = self._load_calibration_pack(positive_parts, "positive", extraction)
|
||||
negatives, skipped_neg = self._load_calibration_pack(negative_parts, "negative", extraction)
|
||||
skipped += skipped_neg
|
||||
return run_calibration(positives, negatives, skipped, self.config)
|
||||
|
||||
@staticmethod
|
||||
def _load_calibration_pack(
|
||||
parts: list[tuple[str, bytes]], group: str, params
|
||||
) -> tuple[list[CalibrationPhoto], list[dict]]:
|
||||
loaded: list[CalibrationPhoto] = []
|
||||
skipped: list[dict] = []
|
||||
for name, data in parts:
|
||||
try:
|
||||
features = extract(data, params)
|
||||
except CvError as exc:
|
||||
skipped.append({"name": name, "group": group, "reason": str(exc)})
|
||||
continue
|
||||
loaded.append(
|
||||
CalibrationPhoto(
|
||||
name=name, group=group, index=-1, features=features,
|
||||
descriptors32=features.descriptors.astype(np.float32),
|
||||
)
|
||||
)
|
||||
return loaded, skipped
|
||||
|
||||
def _load_reference(
|
||||
self, part: bytes, index: int, settings_req: RequestSettings | None
|
||||
) -> tuple[Features, RequestSettings | None]:
|
||||
|
||||
@@ -137,4 +137,6 @@ def _body_limit(path: str, config: Config) -> int | None:
|
||||
return config.verify_max_body_bytes
|
||||
if path == "/api/v1/features":
|
||||
return config.max_image_bytes + _FEATURES_BODY_SLACK_BYTES
|
||||
if path == "/api/v1/calibrate":
|
||||
return config.calibration_max_body_bytes
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user