UFR-Fing / src /data /nist302_loader.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
4.49 kB
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import torch
from PIL import Image
from torchvision import transforms
from .base import FingerprintSample
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"}
@dataclass
class NIST302Paths:
"""Root folders for three NIST SD302 subsets."""
root_302a: str
root_302b: str
root_302d: str
class NIST302Loader:
"""Unified loader for NIST SD302 A/B/D variants.
The loader parses metadata from path and filename patterns currently present
under the workspace dataset tree.
"""
def __init__(self, image_size: int = 224):
self.transform = transforms.Compose(
[
transforms.Resize((image_size, image_size)),
transforms.ToTensor(),
]
)
def discover(self, paths: NIST302Paths) -> list[dict[str, str]]:
records: list[dict[str, str]] = []
for root_str, dataset_name in [
(paths.root_302a, "nist_sd302a"),
(paths.root_302b, "nist_sd302b"),
(paths.root_302d, "nist_sd302d"),
]:
if not root_str: # skip empty roots — Path("") resolves to cwd and scans everything
continue
records.extend(self._scan_subset(Path(root_str), dataset_name))
return records
def iter_samples(
self, records: Iterable[dict[str, str]]
) -> Iterable[FingerprintSample]:
for rec in records:
image = Image.open(rec["image_path"]).convert("L")
tensor = self.transform(image)
yield {
"image": tensor,
"identity_id": rec["identity_id"],
"finger_id": rec["finger_id"],
"sensor_id": rec["sensor_id"],
"dataset": rec["dataset"],
"image_path": rec["image_path"],
}
def _scan_subset(self, subset_root: Path, dataset_name: str) -> list[dict[str, str]]:
if not subset_root.exists():
return []
records: list[dict[str, str]] = []
for path in sorted(subset_root.rglob("*")):
if not path.is_file() or path.suffix.lower() not in IMAGE_EXTS:
continue
meta = self._parse_metadata(path, subset_root, dataset_name)
if meta is not None:
records.append(meta)
return records
@staticmethod
def _parse_metadata(
file_path: Path,
subset_root: Path,
dataset_name: str,
) -> dict[str, str] | None:
rel_parts = file_path.relative_to(subset_root).parts
stem_tokens = file_path.stem.split("_")
# SD302-A filenames have 4 tokens: {subject}_{sensor}_{captype}_{finger}
# SD302-B/D filenames have 5 tokens: {subject}_{sensor}_{dpi}_{captype}_{finger}
if len(stem_tokens) < 4:
return None
identity_id = stem_tokens[0]
# NIST SD302 identity IDs are 8-digit numbers; reject non-fingerprint files early
if not (identity_id.isdigit() and len(identity_id) == 8):
return None
# Heuristic finger id from filename tail. This should be audited before
# strict cross-sensor experiments, matching the plan's risk note.
finger_token = stem_tokens[-1]
finger_id = f"F{int(finger_token):02d}" if finger_token.isdigit() else finger_token
# Sensor token is stabilized from the first 1-3 directory markers that
# capture device/capture style differences.
sensor_tokens = rel_parts[:-1]
sensor_id = "_".join(sensor_tokens[:3]) if sensor_tokens else "unknown"
return {
"identity_id": identity_id,
"finger_id": finger_id,
"sensor_id": sensor_id,
"dataset": dataset_name,
"image_path": str(file_path),
}
def to_batch(samples: list[FingerprintSample]) -> dict[str, torch.Tensor | list[str]]:
"""Collate helper for lists emitted by NIST302Loader.iter_samples."""
images = torch.stack([s["image"] for s in samples], dim=0)
return {
"images": images,
"identity_ids": [s["identity_id"] for s in samples],
"finger_ids": [s["finger_id"] for s in samples],
"sensor_ids": [s["sensor_id"] for s in samples],
"datasets": [s["dataset"] for s in samples],
"image_paths": [s["image_path"] for s in samples],
}