| from __future__ import annotations |
|
|
| """Image-only dataset for the V2 (ViT + TRAM + GNN) pipeline. |
| |
| Unlike ``FingerprintDataset`` which requires paired minutiae files, |
| this dataset loads only images + identity labels. No minutiae extractor |
| is needed — the ViT backbone learns features end-to-end. |
| |
| Supports directory layouts: |
| 1. ImageFolder: ``root/identity_name/sample.{ext}`` |
| 2. PolyU: ``root/{first,second}_session/finger_sample.{ext}`` |
| (identity parsed from filename prefix before last underscore) |
| """ |
|
|
| import os |
| import random |
| from collections import defaultdict |
| from pathlib import Path |
|
|
| import torch |
| from torch.utils.data import Dataset, Sampler |
| from PIL import Image |
|
|
| from .augmentation import build_train_transform, build_val_transform |
|
|
|
|
| IMAGE_EXTS = {".bmp", ".png", ".tif", ".tiff", ".jpg", ".jpeg"} |
|
|
|
|
| def infer_device_from_name(path_or_name: str) -> str | None: |
| stem = Path(path_or_name).stem |
| parts = stem.split("_") |
| if len(parts) < 4: |
| return None |
| token = parts[1] |
| token_lower = token.lower() |
| if token_lower in {"roll", "plain"}: |
| return token_lower |
| if token.isalpha() and len(token) <= 3: |
| return token |
| return None |
|
|
|
|
| class ImageDataset(Dataset): |
| """Load fingerprint images with identity labels for metric learning. |
| |
| Returns: |
| image: ``(1, H, W)`` normalised [0, 1] |
| label: int |
| """ |
|
|
| def __init__( |
| self, |
| image_dir: str, |
| image_size: int = 224, |
| augment: bool = True, |
| repeat_factor: int = 1, |
| augment_profile: str = "standard", |
| ): |
| super().__init__() |
| self.transform = ( |
| build_train_transform(image_size, profile=augment_profile) if augment |
| else build_val_transform(image_size) |
| ) |
| self.repeat_factor = max(1, int(repeat_factor)) |
|
|
| self.samples: list[tuple[str, int]] = [] |
| self.labels: list[int] = [] |
| self.devices: list[str | None] = [] |
| self.label_map: dict[str, int] = {} |
|
|
| self._discover(image_dir) |
|
|
| |
| def _discover(self, image_dir: str): |
| root = Path(image_dir) |
| if not root.exists(): |
| return |
|
|
| subdirs = sorted([d for d in root.iterdir() if d.is_dir()]) |
| session_like = subdirs and all("session" in d.name.lower() for d in subdirs) |
|
|
| if subdirs and not session_like: |
| has_images = any( |
| any(f.suffix.lower() in IMAGE_EXTS for f in d.iterdir() if f.is_file()) |
| for d in subdirs[:5] |
| ) |
| if has_images: |
| self._discover_imagefolder(root, subdirs) |
| return |
|
|
| self._discover_flat(root) |
|
|
| def _append_sample(self, img_path: Path, label: int): |
| self.samples.append((str(img_path), label)) |
| self.labels.append(label) |
| self.devices.append(infer_device_from_name(img_path.name)) |
|
|
| def _discover_imagefolder(self, root: Path, subdirs: list[Path]): |
| """``root/identity/sample.ext`` layout.""" |
| for idx, identity_dir in enumerate(subdirs): |
| identity = identity_dir.name |
| self.label_map[identity] = idx |
| for img_file in sorted(identity_dir.iterdir()): |
| if img_file.suffix.lower() in IMAGE_EXTS: |
| self._append_sample(img_file, idx) |
|
|
| def _discover_flat(self, root: Path): |
| """Flat/PolyU layout — parse identity from filename.""" |
| all_images: list[Path] = [] |
| for ext in IMAGE_EXTS: |
| all_images.extend(root.rglob(f"*{ext}")) |
| all_images = sorted(all_images) |
|
|
| identity_of: dict[str, str] = {} |
| for img in all_images: |
| stem = img.stem |
| parts = stem.rsplit("_", 1) |
| identity = parts[0] if len(parts) > 1 else stem |
| identity_of[str(img)] = identity |
|
|
| unique_ids = sorted(set(identity_of.values())) |
| id_to_label = {name: idx for idx, name in enumerate(unique_ids)} |
| self.label_map = id_to_label |
|
|
| for img in all_images: |
| identity = identity_of[str(img)] |
| label = id_to_label[identity] |
| self._append_sample(img, label) |
|
|
| |
| @property |
| def num_classes(self) -> int: |
| return len(self.label_map) |
|
|
| def __len__(self) -> int: |
| return len(self.samples) * self.repeat_factor |
|
|
| def __getitem__(self, idx: int) -> dict[str, object]: |
| idx = idx % len(self.samples) |
| path, label = self.samples[idx] |
| pil_img = Image.open(path).convert("L") |
| image = self.transform(pil_img) |
| return {"image": image, "label": label} |
|
|
|
|
| class ImageListDataset(Dataset): |
| """Image dataset backed by an explicit list of ``(path, label)`` samples. |
| |
| Useful for continual learning where the effective training set is assembled |
| dynamically from the current stage plus replay exemplars from previous stages. |
| """ |
|
|
| def __init__( |
| self, |
| samples: list[tuple[str, int]], |
| image_size: int = 224, |
| augment: bool = True, |
| augment_profile: str = "standard", |
| ): |
| super().__init__() |
| self.transform = ( |
| build_train_transform(image_size, profile=augment_profile) if augment |
| else build_val_transform(image_size) |
| ) |
| self.samples = [(str(path), int(label)) for path, label in samples] |
| self.labels = [label for _path, label in self.samples] |
| self.devices = [infer_device_from_name(path) for path, _label in self.samples] |
| unique_labels = sorted(set(self.labels)) |
| self.label_map = {str(label): label for label in unique_labels} |
|
|
| @property |
| def num_classes(self) -> int: |
| return len(self.label_map) |
|
|
| def __len__(self) -> int: |
| return len(self.samples) |
|
|
| def __getitem__(self, idx: int) -> dict[str, object]: |
| path, label = self.samples[idx] |
| pil_img = Image.open(path).convert("L") |
| image = self.transform(pil_img) |
| return {"image": image, "label": label} |
|
|
|
|
| class PKSamplerV2(Sampler): |
| """P identities × K samples per batch for metric learning.""" |
|
|
| def __init__(self, dataset: ImageDataset, p: int = 8, k: int = 4, device_aware: bool = False): |
| self.p = p |
| self.k = k |
| self.device_aware = device_aware |
| self._len = len(dataset) // (p * k) |
|
|
| self.label_to_indices: dict[int, list[int]] = defaultdict(list) |
| self.label_to_device_indices: dict[int, dict[str | None, list[int]]] = defaultdict(lambda: defaultdict(list)) |
| for idx, label in enumerate(dataset.labels): |
| self.label_to_indices[label].append(idx) |
| self.label_to_device_indices[label][dataset.devices[idx]].append(idx) |
|
|
| self.labels = sorted(self.label_to_indices.keys()) |
|
|
| def _sample_indices(self, label: int) -> list[int]: |
| indices = self.label_to_indices[label] |
| if not self.device_aware: |
| return ( |
| random.sample(indices, self.k) |
| if len(indices) >= self.k |
| else random.choices(indices, k=self.k) |
| ) |
|
|
| by_device = self.label_to_device_indices[label] |
| distinct_devices = [dev for dev in by_device if dev is not None] |
| if len(distinct_devices) <= 1: |
| return ( |
| random.sample(indices, self.k) |
| if len(indices) >= self.k |
| else random.choices(indices, k=self.k) |
| ) |
|
|
| chosen: list[int] = [] |
| device_keys = distinct_devices.copy() |
| random.shuffle(device_keys) |
| for dev in device_keys: |
| if len(chosen) >= self.k: |
| break |
| chosen.append(random.choice(by_device[dev])) |
|
|
| remaining_pool = [idx for idx in indices if idx not in chosen] |
| needed = self.k - len(chosen) |
| if needed > 0: |
| if len(remaining_pool) >= needed: |
| chosen.extend(random.sample(remaining_pool, needed)) |
| else: |
| chosen.extend(remaining_pool) |
| if len(chosen) < self.k: |
| chosen.extend(random.choices(indices, k=self.k - len(chosen))) |
|
|
| return chosen |
|
|
| def __iter__(self): |
| pool = self.labels.copy() |
| random.shuffle(pool) |
| ptr = 0 |
|
|
| for _ in range(self._len): |
| if ptr + self.p > len(pool): |
| pool = self.labels.copy() |
| random.shuffle(pool) |
| ptr = 0 |
|
|
| batch_labels = pool[ptr:ptr + self.p] |
| ptr += self.p |
|
|
| batch: list[int] = [] |
| for lbl in batch_labels: |
| batch.extend(self._sample_indices(lbl)) |
| yield batch |
|
|
| def __len__(self) -> int: |
| return max(1, self._len) |
|
|