Files
open_cv/app/cv/comparison.py
2026-09-29 00:17:58 +03:00

149 lines
5.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Операция compare: пара «проба–эталон» → метрики, вердикт, confidence.
Схема — docs/04 §4.3–4.4: BFMatcher(kNN=2) → тест Лоу → RANSAC-геометрия
(homography | fundamental) → метрики пары → трёхзонный вердикт.
"""
from __future__ import annotations
import dataclasses
import cv2
import numpy as np
from app.cv.extraction import Features
from app.cv.params import ComparisonParams
# Ниже — константы формулы confidence и RANSAC из docs/04 §4.4 и §4.3:
# это часть спецификации алгоритма, а не конфигурируемые параметры
# (в env-таблице docs/07 §7.4 их нет).
MIN_GOOD_MATCHES = 10
INLIERS_SATURATION = 150.0
COVERAGE_NORM_SATURATION = 0.25
CONFIDENCE_WEIGHTS = (0.6, 0.25, 0.15) # inliers, inlier_ratio, coverage_norm
RANSAC_CONFIDENCE = 0.995
RANSAC_MAX_ITERS = 5000
# ГПСЧ OpenCV фиксируется перед каждым RANSAC-вызовом для детерминизма
# (NFR-009, docs/04 §4.6); seed-политика не входит в algo_id.
RANSAC_SEED = 42
VERDICT_MATCH = "match"
VERDICT_UNCERTAIN = "uncertain"
VERDICT_NO_MATCH = "no_match"
@dataclasses.dataclass(frozen=True)
class PairMetrics:
good_matches: int
inliers: int
inlier_ratio: float
coverage: float
@dataclasses.dataclass(frozen=True)
class PairResult:
metrics: PairMetrics
verdict: str
confidence: float
thresholds: ComparisonParams
def _zero_metrics(good_matches: int = 0) -> PairMetrics:
return PairMetrics(good_matches=good_matches, inliers=0, inlier_ratio=0.0, coverage=0.0)
def _confidence(metrics: PairMetrics) -> float:
inliers_part = (metrics.inliers / INLIERS_SATURATION) * CONFIDENCE_WEIGHTS[0]
ratio_part = metrics.inlier_ratio * CONFIDENCE_WEIGHTS[1]
coverage_norm = min(metrics.coverage / COVERAGE_NORM_SATURATION, 1.0)
coverage_part = coverage_norm * CONFIDENCE_WEIGHTS[2]
return float(min(1.0, max(0.0, inliers_part + ratio_part + coverage_part)))
def _verdict(metrics: PairMetrics, params: ComparisonParams) -> str:
if (
metrics.inliers >= params.match_inliers_min
and metrics.inlier_ratio >= params.match_inliers_ratio_min
and metrics.coverage >= params.match_coverage_min
):
return VERDICT_MATCH
if metrics.inliers >= params.uncertain_inliers_min:
return VERDICT_UNCERTAIN
return VERDICT_NO_MATCH
def _coverage(probe_pts: np.ndarray, mask: np.ndarray, probe: Features) -> float:
"""Доля площади изображения пробы под выпуклой оболочкой инлаеров."""
inliers = probe_pts[mask.reshape(-1) == 1]
if inliers.shape[0] < 3:
return 0.0
hull = cv2.convexHull(inliers.astype(np.float32))
area = cv2.contourArea(hull)
total = float(probe.width) * float(probe.height)
if total <= 0:
return 0.0
return float(min(area / total, 1.0))
def _ransac_inliers(
ref_pts: np.ndarray, probe_pts: np.ndarray, params: ComparisonParams
) -> np.ndarray | None:
"""Геометрическая проверка RANSAC; возвращает маску инлаеров или None."""
cv2.setRNGSeed(RANSAC_SEED)
if params.geometry_model == "fundamental":
_, mask = cv2.findFundamentalMat(
ref_pts, probe_pts,
cv2.RANSAC,
params.ransac_reproj_threshold,
RANSAC_CONFIDENCE,
RANSAC_MAX_ITERS,
)
else:
_, mask = cv2.findHomography(
ref_pts, probe_pts,
cv2.RANSAC,
params.ransac_reproj_threshold,
maxIters=RANSAC_MAX_ITERS,
confidence=RANSAC_CONFIDENCE,
)
return mask
def compare_features(probe: Features, ref: Features, params: ComparisonParams) -> PairResult:
"""Сравнение пары «проба–эталон» эффективными параметрами сравнения."""
if probe.count < 2 or ref.count < 2:
return PairResult(_zero_metrics(), VERDICT_NO_MATCH, 0.0, params)
matcher = cv2.BFMatcher(normType=cv2.NORM_L2, crossCheck=False)
matches = matcher.knnMatch(probe.descriptors.astype(np.float32),
ref.descriptors.astype(np.float32), k=2)
# Тест Лоу: лучший матч должен быть существенно лучше второго (docs/04 §4.3)
pairs = [
(row[0].queryIdx, row[0].trainIdx)
for row in matches
if len(row) == 2 and row[0].distance < params.lowe_ratio * row[1].distance
]
good_matches = len(pairs)
if good_matches < MIN_GOOD_MATCHES:
metrics = _zero_metrics(good_matches)
return PairResult(metrics, VERDICT_NO_MATCH, _confidence(metrics), params)
probe_kp = probe.keypoints[:, :2]
ref_kp = ref.keypoints[:, :2]
probe_pts = np.array([probe_kp[q] for q, _ in pairs], dtype=np.float32)
ref_pts = np.array([ref_kp[t] for _, t in pairs], dtype=np.float32)
mask = _ransac_inliers(ref_pts, probe_pts, params)
if mask is None or mask.size == 0:
metrics = _zero_metrics(good_matches) # модель не найдена → no_match (docs/04 §4.4)
return PairResult(metrics, VERDICT_NO_MATCH, _confidence(metrics), params)
inliers = int(np.count_nonzero(mask))
metrics = PairMetrics(
good_matches=good_matches,
inliers=inliers,
inlier_ratio=inliers / good_matches,
coverage=_coverage(probe_pts, mask, probe),
)
return PairResult(metrics, _verdict(metrics, params), _confidence(metrics), params)