File size: 2,537 Bytes
dadf189 | 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 | from __future__ import annotations
import json
import random
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class PairRecord:
path_s1: str
path_s2: str
identity_id: str
finger_id: str
sensor_s1: str
sensor_s2: str
dataset: str
def build_cross_sensor_pairs(
samples: list[dict[str, str]],
dataset: str,
min_sensors: int = 2,
max_pairs_per_finger: int = 5,
seed: int = 42,
) -> list[PairRecord]:
"""Build cross-sensor pairs for the same identity/finger tuple."""
rng = random.Random(seed)
grouped: dict[tuple[str, str], list[dict[str, str]]] = defaultdict(list)
for sample in samples:
if sample.get("dataset") != dataset:
continue
key = (sample["identity_id"], sample["finger_id"])
grouped[key].append(sample)
all_pairs: list[PairRecord] = []
for (identity_id, finger_id), items in grouped.items():
by_sensor: dict[str, list[dict[str, str]]] = defaultdict(list)
for item in items:
by_sensor[item["sensor_id"]].append(item)
if len(by_sensor) < min_sensors:
continue
sensor_names = sorted(by_sensor.keys())
candidate_pairs: list[PairRecord] = []
for i, sensor_a in enumerate(sensor_names):
for sensor_b in sensor_names[i + 1 :]:
for sa in by_sensor[sensor_a]:
for sb in by_sensor[sensor_b]:
candidate_pairs.append(
PairRecord(
path_s1=sa["image_path"],
path_s2=sb["image_path"],
identity_id=identity_id,
finger_id=finger_id,
sensor_s1=sensor_a,
sensor_s2=sensor_b,
dataset=dataset,
)
)
if len(candidate_pairs) > max_pairs_per_finger:
candidate_pairs = rng.sample(candidate_pairs, max_pairs_per_finger)
all_pairs.extend(candidate_pairs)
return all_pairs
def export_pairs_json(pairs: list[PairRecord], output_path: str) -> None:
"""Write pair records to disk as JSON list."""
path = Path(output_path)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
json.dump([p.__dict__ for p in pairs], f, indent=2)
|