160 lines
8.0 KiB
Python
160 lines
8.0 KiB
Python
"""Юнит-тесты извлечения и сравнения — docs/08 §8.2, UT-01..UT-09, UT-17."""
|
|
from __future__ import annotations
|
|
|
|
import cv2
|
|
import numpy as np
|
|
import pytest
|
|
|
|
from app.cv.comparison import PairResult, compare_features
|
|
from app.cv.extraction import extract
|
|
from app.cv.params import ComparisonParams, base_extraction, base_comparison
|
|
from tests import synth
|
|
from tests.conftest import make_config
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def config():
|
|
return make_config()
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def features_pair(config):
|
|
"""Признаки базового «фасада» и его копии — общая база для UT-01..UT-08."""
|
|
base = synth.encode_jpg(synth.make_facade(seed=7))
|
|
f1 = extract(base, base_extraction(config))
|
|
f2 = extract(base, base_extraction(config))
|
|
return f1, f2
|
|
|
|
|
|
def _compare(config, probe, ref, **overrides) -> PairResult:
|
|
params = base_comparison(config)
|
|
if overrides:
|
|
params = ComparisonParams(**{**vars(params), **overrides})
|
|
return compare_features(probe, ref, params)
|
|
|
|
|
|
class TestExtractionComparison:
|
|
def test_ut01_photo_vs_copy(self, config, features_pair):
|
|
"""UT-01: фото vs копия — match, высокий confidence, inlier_ratio ≥ 0.8."""
|
|
f1, f2 = features_pair
|
|
result = _compare(config, f1, f2)
|
|
assert result.verdict == "match"
|
|
assert result.confidence >= 0.6
|
|
assert result.metrics.inlier_ratio >= 0.8
|
|
|
|
def test_ut02_photo_vs_warped(self, config):
|
|
"""UT-02: проективно искажённая копия — match."""
|
|
base = synth.make_facade(seed=7)
|
|
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
|
f2 = extract(synth.encode_jpg(synth.warp_perspective(base)), base_extraction(config))
|
|
result = _compare(config, f1, f2)
|
|
assert result.verdict == "match"
|
|
|
|
def test_ut03_photo_vs_half(self, config):
|
|
"""UT-03: уменьшенная копия (0.5×) — match.
|
|
|
|
База берётся 1600×1200, чтобы уменьшенная копия (800×600) оставалась
|
|
выше минимального разрешения 640×480.
|
|
"""
|
|
base = synth.make_facade(seed=7, width=1600, height=1200)
|
|
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
|
f2 = extract(synth.encode_jpg(synth.scale_half(base)), base_extraction(config))
|
|
result = _compare(config, f1, f2)
|
|
assert result.verdict == "match"
|
|
|
|
def test_ut04_photo_vs_other_building(self, config):
|
|
"""UT-04: другое здание — no_match или uncertain, но не match."""
|
|
f1 = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config))
|
|
f2 = extract(synth.encode_jpg(synth.make_facade(seed=99)), base_extraction(config))
|
|
result = _compare(config, f1, f2)
|
|
assert result.verdict in ("no_match", "uncertain")
|
|
|
|
def test_ut05_photo_vs_other_angle(self, config):
|
|
"""UT-05: тот же объект, другой ракурс — match при «широком» ракурсе."""
|
|
base = synth.make_facade(seed=7)
|
|
h, w = base.shape[:2]
|
|
src = np.float32([[0, 0], [w, 0], [w, h], [0, h]])
|
|
dst = np.float32(
|
|
[[w * 0.08, h * 0.06], [w * 0.97, h * 0.10], [w * 0.88, h * 0.95], [w * 0.10, h * 0.92]]
|
|
)
|
|
m = cv2.getPerspectiveTransform(src, dst)
|
|
other_angle = cv2.warpPerspective(base, m, (w, h))
|
|
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
|
f2 = extract(synth.encode_jpg(other_angle), base_extraction(config))
|
|
assert _compare(config, f1, f2).verdict == "match"
|
|
|
|
def test_ut06_cropped_fragment(self, config):
|
|
"""UT-06: фрагмент как эталон — coverage корректно мал.
|
|
|
|
Проба — полный кадр, эталон — кроп 60 %: инлаеры покрывают только
|
|
область фрагмента (защита от «локального совпадения» — 04 §4.3).
|
|
Кроп 60 % сохраняет разрешение выше 640×480.
|
|
"""
|
|
base = synth.make_facade(seed=7)
|
|
f_full = extract(synth.encode_jpg(base), base_extraction(config))
|
|
f_crop = extract(synth.encode_jpg(synth.crop_center(base, fraction=0.6)),
|
|
base_extraction(config))
|
|
result = _compare(config, f_full, f_crop)
|
|
assert result.verdict in ("uncertain", "match")
|
|
assert result.metrics.coverage == pytest.approx(0.6 * 0.6, abs=0.15)
|
|
|
|
def test_ut07_poor_texture(self, config):
|
|
"""UT-07: однотонная заливка — мало keypoints, деградация без исключений."""
|
|
features = extract(synth.encode_jpg(synth.make_flat()), base_extraction(config))
|
|
assert features.count < 500
|
|
other = extract(synth.encode_jpg(synth.make_facade(seed=3)), base_extraction(config))
|
|
result = _compare(config, features, other) # не должно упасть
|
|
assert result.verdict in ("no_match", "uncertain")
|
|
|
|
def test_ut08_determinism(self, config, features_pair):
|
|
"""UT-08: повторный compare тех же входов — идентичные метрики (NFR-009)."""
|
|
f1, f2 = features_pair
|
|
first = _compare(config, f1, f2)
|
|
second = _compare(config, f1, f2)
|
|
assert first.metrics == second.metrics
|
|
assert first.verdict == second.verdict
|
|
assert first.confidence == second.confidence
|
|
|
|
def test_ut09_preprocessing(self, config):
|
|
"""UT-09: EXIF-ориентация, ресайз, CLAHE — корректные размеры/типы."""
|
|
from app.cv.extraction import decode_image, _preprocess
|
|
from app.cv.params import ExtractionParams
|
|
|
|
# EXIF-ориентация 6 (поворот 90°): размеры меняются местами
|
|
raw = synth.make_facade(seed=11, width=1400, height=900)
|
|
exif_jpg = synth.encode_exif_oriented(raw, orientation=6)
|
|
_, width, height = decode_image(exif_jpg)
|
|
assert (width, height) == (900, 1400)
|
|
|
|
# ресайз до max_image_size длинной стороны
|
|
params = ExtractionParams(max_image_size=800, max_keypoints=4096,
|
|
clahe_clip_limit=2.0, clahe_tile_grid=(8, 8))
|
|
gray, w, h = _preprocess(np.asarray(cv2.cvtColor(raw, cv2.COLOR_BGR2RGB)), params)
|
|
assert max(w, h) <= 800
|
|
assert gray.dtype == np.uint8 and gray.ndim == 2
|
|
|
|
# CLAHE не меняет размеров и тип
|
|
assert (w, h) == (gray.shape[1], gray.shape[0])
|
|
|
|
def test_ut17_fundamental_model(self, config):
|
|
"""UT-17: fundamental на синтетической паре — метрики считаются и
|
|
детерминированы; обе модели дают согласованные вердикты.
|
|
|
|
Сравнение абсолютных чисел инлаеров H vs F на плоской синтетике
|
|
нестабильно (порог F — расстояние до эпиполярной линии, не пиксели
|
|
репроекции), поэтому проверяется вычислимость и детерминизм.
|
|
"""
|
|
base = synth.make_facade(seed=7)
|
|
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
|
f2 = extract(synth.encode_jpg(synth.warp_perspective(base)), base_extraction(config))
|
|
|
|
fund_a = _compare(config, f1, f2, geometry_model="fundamental")
|
|
fund_b = _compare(config, f1, f2, geometry_model="fundamental")
|
|
homo = _compare(config, f1, f2, geometry_model="homography")
|
|
|
|
assert fund_a.metrics.inliers > 0 # метрики считаются
|
|
assert fund_a.metrics == fund_b.metrics # детерминизм
|
|
assert fund_a.confidence == fund_b.confidence
|
|
assert homo.metrics.inliers > 0
|
|
assert homo.verdict == fund_a.verdict # согласованность моделей
|