UFR-Fing / src /data /dataset.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
10.5 kB
from __future__ import annotations
"""Dataset for fingerprint images + pre-extracted minutiae.
Supports two directory layouts:
1. **Paired layout** (image_dir and minutiae_dir separate):
image_dir/<identity>/<sample>.{bmp,png,tif,jpg}
minutiae_dir/<identity>/<sample>.txt
2. **PolyU layout** (images in session dirs, minutiae in processed dir):
image_root/first_session/{finger_id}_{num}.jpg
minutiae_root/{split}/finger_{finger_id}/{session}_{finger_id}_{num}.txt
Each minutiae .txt file has one minutia per line: ``x y theta [type]``.
"""
import os
import random
from collections import defaultdict
from pathlib import Path
from typing import Any
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset, Sampler
from torchvision import transforms
from ..configs.default import AugmentConfig, DataConfig
from .joint_augmentor import JointAugmentor
class FingerprintDataset(Dataset):
"""Loads fingerprint images paired with pre-extracted minutiae .txt files.
Returns dict:
image: (1, H, W) normalized [0, 1]
minutiae_raw: (max_N, 3) pixel [x, y, theta]
mask: (max_N,) bool
label: int
"""
IMAGE_EXTENSIONS = {".bmp", ".png", ".tif", ".tiff", ".jpg", ".jpeg"}
def __init__(
self,
image_dir: str,
minutiae_dir: str,
image_size: tuple[int, int] = (256, 256),
max_minutiae: int = 120,
min_minutiae: int = 10,
augment: bool = True,
augment_cfg: AugmentConfig | None = None,
):
super().__init__()
self.image_size = image_size
self.max_minutiae = max_minutiae
self.min_minutiae = min_minutiae
self.augmentor = (
JointAugmentor(augment_cfg or AugmentConfig()) if augment else None
)
self.to_tensor = transforms.ToTensor()
self.samples: list[tuple[str, str, int]] = [] # (img_path, txt_path, label)
self.label_map: dict[str, int] = {}
self._discover_samples(image_dir, minutiae_dir)
def _discover_samples(self, image_dir: str, minutiae_dir: str):
"""Scan directories and pair images with minutiae files."""
image_root = Path(image_dir)
minutiae_root = Path(minutiae_dir)
if not image_root.exists() or not minutiae_root.exists():
return
for idx, identity_dir in enumerate(sorted(minutiae_root.iterdir())):
if not identity_dir.is_dir():
continue
identity_name = identity_dir.name
self.label_map[identity_name] = idx
for txt_file in sorted(identity_dir.glob("*.txt")):
img_path = self._find_matching_image(
txt_file, image_root, identity_name
)
if img_path is not None:
self.samples.append((str(img_path), str(txt_file), idx))
def _find_matching_image(
self, txt_file: Path, image_root: Path, identity_name: str
) -> Path | None:
"""Find the image file corresponding to a minutiae .txt file.
Supports multiple dataset layouts:
- Paired: image_root/identity/sample.{ext}
- PolyU: image_root/{first,second}_session/finger_sample.{ext}
- FVC: image_root/FVC20XX/Dbs/DbN_{a,b}/finger_impr.{ext}
"""
stem = txt_file.stem
# Strategy 1: same directory structure (paired layout)
for ext in self.IMAGE_EXTENSIONS:
candidate = image_root / identity_name / f"{stem}{ext}"
if candidate.exists():
return candidate
# Strategy 2: PolyU layout — txt stem "s1_101_3" -> first_session/101_3.jpg
if stem.startswith(("s1_", "s2_")):
session_prefix = stem[:2]
original_name = stem[3:]
session_dir = (
"first_session" if session_prefix == "s1" else "second_session"
)
for ext in self.IMAGE_EXTENSIONS:
candidate = image_root / session_dir / f"{original_name}{ext}"
if candidate.exists():
return candidate
# Strategy 3: FVC layout — identity "fvc2000_db1_a_001", stem "1_3"
# -> image_root/FVC2000/Dbs/Db1_a/1_3.tif
if identity_name.startswith("fvc"):
parts = identity_name.split("_") # ["fvc2000", "db1", "a", "001"]
if len(parts) >= 3:
version = parts[0].upper().replace("FVC", "FVC") # "FVC2000"
db_set = f"{parts[1].capitalize()}_{parts[2]}" # "Db1_a"
for ext in self.IMAGE_EXTENSIONS:
candidate = image_root / version / "Dbs" / db_set / f"{stem}{ext}"
if candidate.exists():
return candidate
# Strategy 4: recursive search (fallback)
for ext in self.IMAGE_EXTENSIONS:
matches = list(image_root.rglob(f"{stem}{ext}"))
if matches:
return matches[0]
return None
@property
def num_classes(self) -> int:
return len(self.label_map)
@staticmethod
def _load_minutiae(path: str) -> torch.Tensor:
"""Read minutiae file -> (N, 3) tensor [x, y, theta]."""
rows = []
with open(path) as f:
for line in f:
parts = line.strip().split()
if len(parts) >= 3:
x, y, theta = float(parts[0]), float(parts[1]), float(parts[2])
rows.append([x, y, theta])
if len(rows) == 0:
return torch.zeros(1, 3)
return torch.tensor(rows, dtype=torch.float32)
def _scale_minutiae(
self,
minutiae: torch.Tensor,
orig_size: tuple[int, int],
) -> torch.Tensor:
"""Scale minutiae (x, y) from original image coords to resized coords."""
orig_h, orig_w = orig_size
target_h, target_w = self.image_size
m = minutiae.clone()
m[:, 0] *= target_w / orig_w
m[:, 1] *= target_h / orig_h
return m
def _pad_or_truncate(
self, minutiae: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
"""Pad/truncate to max_minutiae; return (padded, mask)."""
N = minutiae.shape[0]
if N > self.max_minutiae:
perm = torch.randperm(N)[: self.max_minutiae]
minutiae = minutiae[perm]
N = self.max_minutiae
padded = torch.zeros(self.max_minutiae, 3)
padded[:N] = minutiae
mask = torch.zeros(self.max_minutiae, dtype=torch.bool)
mask[:N] = True
return padded, mask
def __len__(self) -> int:
return len(self.samples)
def __getitem__(self, idx: int, _depth: int = 0) -> dict[str, Any]:
img_path, txt_path, label = self.samples[idx]
# Load image
pil_img = Image.open(img_path).convert("L")
orig_w, orig_h = pil_img.size
pil_img = pil_img.resize(
(self.image_size[1], self.image_size[0]), Image.BILINEAR
)
image = self.to_tensor(pil_img)
# Load minutiae and scale to resized image coords
minutiae = self._load_minutiae(txt_path)
minutiae = self._scale_minutiae(minutiae, (orig_h, orig_w))
# Skip too-small samples
if minutiae.shape[0] < self.min_minutiae:
if _depth < len(self):
return self.__getitem__((idx + 1) % len(self), _depth + 1)
minutiae = torch.zeros(1, 3)
# Joint augmentation
if self.augmentor is not None:
image, minutiae = self.augmentor(image, minutiae)
# Pad/truncate
minutiae_raw, mask = self._pad_or_truncate(minutiae)
return {
"image": image,
"minutiae_raw": minutiae_raw,
"mask": mask,
"label": label,
}
class PKSampler(Sampler):
"""P identities x K samples per identity for metric learning."""
def __init__(self, dataset: FingerprintDataset, p: int = 8, k: int = 4):
self.dataset = dataset
self.p = p
self.k = k
self.label_to_indices: dict[int, list[int]] = defaultdict(list)
for idx, (_, _, label) in enumerate(dataset.samples):
self.label_to_indices[label].append(idx)
self.labels = [l for l, idxs in self.label_to_indices.items() if len(idxs) >= k]
if len(self.labels) < p:
self.labels = list(self.label_to_indices.keys())
def __iter__(self):
label_pool = self.labels.copy()
random.shuffle(label_pool)
batches_yielded = 0
target_batches = len(self)
ptr = 0
while batches_yielded < target_batches:
if ptr + self.p > len(label_pool):
label_pool = self.labels.copy()
random.shuffle(label_pool)
ptr = 0
batch_labels = label_pool[ptr : ptr + self.p]
ptr += self.p
batch = []
for label in batch_labels:
indices = self.label_to_indices[label]
if len(indices) >= self.k:
chosen = random.sample(indices, self.k)
else:
chosen = random.choices(indices, k=self.k)
batch.extend(chosen)
yield batch
batches_yielded += 1
def __len__(self):
return len(self.dataset) // (self.p * self.k)
def build_dataloader(
cfg: DataConfig,
split: str = "train",
batch_size: int = 32,
image_root: str | None = None,
) -> DataLoader:
"""Build a DataLoader for the model.
Args:
cfg: DataConfig with dirs, sizes, etc.
split: "train" or "val".
batch_size: batch size.
image_root: override for image directory root.
"""
augment = split == "train"
minutiae_dir = os.path.join(cfg.minutiae_dir, split)
img_dir = image_root or cfg.image_dir
ds = FingerprintDataset(
image_dir=img_dir,
minutiae_dir=minutiae_dir,
image_size=cfg.image_size,
max_minutiae=cfg.max_minutiae,
min_minutiae=cfg.min_minutiae,
augment=augment,
augment_cfg=cfg.augment if augment else None,
)
return DataLoader(
ds,
batch_size=batch_size,
shuffle=(split == "train"),
num_workers=cfg.num_workers,
pin_memory=cfg.pin_memory,
drop_last=(split == "train"),
)