feature_consistency.py
3.84 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""Compare base features with V3 source or saved V3 features.
Run from the worktree with python -m tools.feature_consistency. Saved features
use one <image filename>.npz per image, with cnn_vector, orb_kp and orb_desc
arrays. Empty ORB arrays represent absent keypoints and descriptors.
"""
import argparse
from hashlib import sha256
import json
from pathlib import Path
from types import ModuleType
import numpy as np
from core.feature_extractor import CNN_VECTOR_DIM, FeatureExtractor
COSINE_MIN = 0.9999
def load_v3(path):
module = ModuleType('v3_feature_extractor')
module.__file__ = str(path)
source = path.read_bytes()
# Execute the supplied working-tree bytes without writing a pyc into V3.
exec(compile(source, str(path), 'exec'), module.__dict__)
return module.FeatureExtractor().extract_all_features, sha256(source).hexdigest()
def _vector(features):
return np.asarray(features.get('cnn_vector'), dtype=np.float64)
def _orb_bytes_equal(left, right):
if left is None or right is None:
return left is right
return left.shape == right.shape and left.dtype == right.dtype and left.tobytes() == right.tobytes()
def compare_features(paths, extract, reference):
results = []
for path in paths:
actual = extract(path) or {}
expected = reference(path) or {}
left, right = _vector(actual), _vector(expected)
cosine = None
if left.shape == right.shape == (CNN_VECTOR_DIM,):
denominator = np.linalg.norm(left) * np.linalg.norm(right)
if np.isfinite(denominator) and denominator > 0:
cosine = float(np.clip(np.dot(left, right) / denominator, -1, 1))
coords = expected.get('orb_kp')
if coords is not None and not isinstance(coords, np.ndarray):
coords = np.float32([point.pt for point in coords]).reshape(-1, 2)
descriptors = expected.get('orb_desc')
if coords is not None and coords.size == 0 and descriptors is not None and descriptors.size == 0:
coords = descriptors = None
results.append({
'image': path.name,
'cosine': cosine,
'orb_coords_equal': _orb_bytes_equal(actual.get('orb_kp'), coords),
'orb_descriptors_equal': _orb_bytes_equal(actual.get('orb_desc'), descriptors),
})
cosines = [row['cosine'] for row in results if row['cosine'] is not None]
summary = {
'images': len(results),
'min_cosine': min(cosines, default=None),
'cnn_mismatches': sum(row['cosine'] is None or row['cosine'] < COSINE_MIN for row in results),
'orb_descriptor_mismatches': sum(not row['orb_descriptors_equal'] for row in results),
'orb_coordinate_mismatches': sum(not row['orb_coords_equal'] for row in results),
}
return summary, results
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('images', nargs='+', type=Path)
reference = parser.add_mutually_exclusive_group(required=True)
reference.add_argument('--v3-module', type=Path)
reference.add_argument('--reference-dir', type=Path)
args = parser.parse_args()
import torch
torch.set_num_threads(1)
source_digest = None
if args.v3_module:
extract_reference, source_digest = load_v3(args.v3_module)
else:
def extract_reference(path):
with np.load(args.reference_dir / (path.name + '.npz'), allow_pickle=False) as saved:
return {key: saved[key] for key in ('cnn_vector', 'orb_kp', 'orb_desc')}
summary, images = compare_features(args.images, FeatureExtractor().extract_all_features, extract_reference)
print(json.dumps({'summary': summary, 'v3_module_sha256': source_digest, 'images': images}, indent=2))
return int(any(summary[key] for key in summary if key.endswith('_mismatches')))
if __name__ == '__main__':
raise SystemExit(main())