File size: 4,137 Bytes
1d21e88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ca097e
1d21e88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""Compare viewpoint patch validation, radial prior and native flow on cached matches."""
import json
import sys
from pathlib import Path
import cv2
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from scripts.benchmark_improvements import common_evaluation
from backend.experimental.patch_validation import validate_geometry_patches
from backend.experimental.evaluation import evaluate_correspondences, fit_geometry
from backend.experimental.mesh import dense_mesh
from backend.experimental.native_refinement import refine_native
from backend.experimental.preprocessing import iris_mask, glare_mask
from backend.experimental.segmentation import adaptive_mask
from backend.compositing import compose

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT/'private_benchmarks/refinement_ablation'


def main():
    OUT.mkdir(exist_ok=True)
    rows = []
    for sample in range(1, 7):
        ref, mov = (cv2.imread(str(ROOT/f'private_benchmarks/client_iris/{sample}/{name}.png')) for name in ('reference', 'moving'))
        original = np.load(ROOT/f'private_benchmarks/research/{sample}-loftr-matches.npz')
        anchors = np.load(ROOT/f'private_benchmarks/research/{sample}-loftr_patch-matches.npz')
        dest = OUT/str(sample)
        dest.mkdir(exist_ok=True)
        a, b = validate_geometry_patches(ref, mov, original['reference'], original['moving'])
        np.savez_compressed(dest/'verified.npz', reference=a, moving=b)
        row = dict(sample=sample, verified_matches=len(a), self_evaluation=evaluate_correspondences(a, b, ref.shape[:2]),
                   common_evaluation=common_evaluation(a, b, anchors['reference'], anchors['moving'], ref.shape[:2]))
        _, geometry = adaptive_mask(ref)
        if geometry is not None and geometry.limbus_detected:
            row['radial_common_evaluation'] = common_evaluation(a, b, anchors['reference'], anchors['moving'], ref.shape[:2], geometry)
        ev = row['self_evaluation']
        if ev['p95_px'] is not None and ev['p95_px'] < 12 and ev['median_px'] < 4:
            matrix, coefficients, _, _ = fit_geometry(a, b, ref.shape[:2])
            mapping, valid, _ = dense_mesh(coefficients, matrix, ref.shape[:2])
            support = np.zeros(ref.shape[:2], np.uint8)
            for point in a:
                cv2.circle(support, tuple(np.rint(point).astype(int)), round(ref.shape[1]*.04), 1, -1)
            support = support.astype(bool)&iris_mask(ref)&valid
            aligned = cv2.remap(mov, mapping[..., 0], mapping[..., 1], cv2.INTER_LINEAR)
            support &= cv2.remap(iris_mask(mov).astype(np.uint8), mapping[..., 0], mapping[..., 1], cv2.INTER_NEAREST).astype(bool)
            trusted = support&~glare_mask(ref)&~glare_mask(aligned)
            refined, diagnostics = refine_native(ref, mov, mapping, trusted)
            row['native_refinement'] = diagnostics
            # Compare displacement at fixed labels, but do not label in-sample flow as CV accuracy.
            for label, map_ in [('mesh', mapping), ('native', refined)]:
                ap, bp = anchors['reference'], anchors['moving']
                prediction = cv2.remap(map_, ap[:, 0:1].astype(np.float32), ap[:, 1:2].astype(np.float32), cv2.INTER_LINEAR)[:, 0]
                error = np.linalg.norm(prediction-bp, axis=1)
                row[label+'_anchor_disagreement'] = dict(median_px=float(np.median(error)), p95_px=float(np.percentile(error, 95)), description='Diagnostic on full-image fit, NOT held-out accuracy.')
            if valid[iris_mask(ref)].mean() >= .99:
                images, _ = compose(ref, aligned, valid, trusted, True)
                for name, image in images.items():
                    cv2.imwrite(str(dest/f'{name}.png'), image)
                np.savez_compressed(dest/'mapping.npz', mapping=mapping)
                cv2.imwrite(str(dest/'native-candidate.png'), cv2.remap(mov, refined[..., 0], refined[..., 1], cv2.INTER_LINEAR))
        rows.append(row)
        (OUT/'results.json').write_text(json.dumps(rows, indent=2))
        print(json.dumps(row), flush=True)


if __name__ == '__main__':
    main()