File size: 6,588 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | from __future__ import annotations
from pathlib import Path
from typing import Iterable
from PIL import Image
from torchvision import transforms
from .base import FingerprintSample
IMAGE_EXTS = {".jpg", ".jpeg", ".bmp", ".png"}
class PolyULoader:
"""Loader for the PolyU Contactless-2D-to-Contact-based Fingerprint Database.
Reference:
Chenhao Lin, Ajay Kumar, "Matching Contactless and Contact-based
Conventional Fingerprint Images for Biometrics Identification,"
IEEE Transactions on Image Processing, vol. 27, pp. 2008-2021, 2018.
Directory layout under ``root_polyu``::
contact-based_fingerprints/
first_session/{X}_{Y}.jpg X=subject_id, Y=impression (1-6)
second_session/{X}_{Y}.jpg
processed_contactless_2d_fingerprint_images/
first_session/p{X}/p{Y}.bmp
second_session/p{X}/p{Y}.bmp
The raw contactless images (1400×900, ~3.6 MB) are **not** loaded; the
pre-downsampled grayscale versions in
``processed_contactless_2d_fingerprint_images`` are used instead.
Metadata fields:
identity_id — ``polyu_{X}`` (shared between contact and contactless)
finger_id — ``f01`` (one finger per subject in this DB)
sensor_id — ``polyu_contact`` | ``polyu_contactless``
dataset — ``polyu``
Cross-modality signal for L_sens:
Same (identity_id, finger_id) appears under two sensor_ids, making these
the strongest possible cross-sensor anchor pairs for GRL training.
"""
SENSOR_CONTACT = "polyu_contact"
SENSOR_CONTACTLESS = "polyu_contactless"
DATASET = "polyu"
SESSIONS = ("first_session", "second_session")
def __init__(self, image_size: int = 224):
self.transform = transforms.Compose(
[
transforms.Resize((image_size, image_size)),
transforms.ToTensor(),
]
)
def discover(self, root_polyu: str) -> list[dict[str, str]]:
"""Scan the PolyU root directory and return a list of metadata records.
Args:
root_polyu: Path to the PolyU root folder (the folder containing
``contact-based_fingerprints`` and
``processed_contactless_2d_fingerprint_images``).
Returns:
List of dicts with keys: image_path, identity_id, finger_id,
sensor_id, dataset.
"""
root = Path(root_polyu)
if not root.exists():
raise FileNotFoundError(f"PolyU root not found: {root}")
records: list[dict[str, str]] = []
records.extend(self._scan_contact(root))
records.extend(self._scan_contactless(root))
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"],
}
# ------------------------------------------------------------------
# Private helpers
# ------------------------------------------------------------------
def _scan_contact(self, root: Path) -> list[dict[str, str]]:
"""Scan contact-based_fingerprints/{session}/{X}_{Y}.jpg."""
folder = root / "contact-based_fingerprints"
records: list[dict[str, str]] = []
if not folder.exists():
return records
for session in self.SESSIONS:
session_dir = folder / session
if not session_dir.exists():
continue
for img_path in sorted(session_dir.iterdir()):
if not img_path.is_file():
continue
if img_path.suffix.lower() not in IMAGE_EXTS:
continue
meta = self._parse_contact_filename(img_path)
if meta is not None:
records.append(meta)
return records
def _scan_contactless(self, root: Path) -> list[dict[str, str]]:
"""Scan processed_contactless_2d_fingerprint_images/{session}/p{X}/p{Y}.bmp."""
folder = root / "processed_contactless_2d_fingerprint_images"
records: list[dict[str, str]] = []
if not folder.exists():
return records
for session in self.SESSIONS:
session_dir = folder / session
if not session_dir.exists():
continue
# Each subject has a subdirectory named p{X}
for subj_dir in sorted(session_dir.iterdir()):
if not subj_dir.is_dir():
continue
subj_name = subj_dir.name # e.g. "p42"
if not subj_name.lower().startswith("p"):
continue
try:
subject_id = str(int(subj_name[1:]))
except ValueError:
continue
identity_id = f"polyu_{subject_id}"
for img_path in sorted(subj_dir.iterdir()):
if not img_path.is_file():
continue
if img_path.suffix.lower() not in IMAGE_EXTS:
continue
records.append(
{
"image_path": str(img_path),
"identity_id": identity_id,
"finger_id": "f01",
"sensor_id": self.SENSOR_CONTACTLESS,
"dataset": self.DATASET,
}
)
return records
@staticmethod
def _parse_contact_filename(img_path: Path) -> dict[str, str] | None:
"""Parse '{X}_{Y}.jpg' → identity_id='polyu_{X}'."""
stem = img_path.stem # e.g. "42_3"
parts = stem.split("_")
if len(parts) != 2:
return None
try:
subject_id = str(int(parts[0]))
except ValueError:
return None
return {
"image_path": str(img_path),
"identity_id": f"polyu_{subject_id}",
"finger_id": "f01",
"sensor_id": PolyULoader.SENSOR_CONTACT,
"dataset": PolyULoader.DATASET,
}
|