File size: 5,356 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
from __future__ import annotations

from dataclasses import dataclass, field
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 FVCPaths:
    """Root directories for FVC years to include.

    Each entry is the 'Dbs' folder (or parent of Dbs).
    Example:
        root_fvc2002 = "/path/to/FVC_Dataset/FVC2002"
        root_fvc2004 = "/path/to/FVC_Dataset/FVC2004"
    Leave empty string to skip a year.
    """

    root_fvc2002: str = ""
    root_fvc2004: str = ""
    root_fvc2000: str = ""
    extra_roots: list[str] = field(default_factory=list)


class FVCLoader:
    """Loader for FVC 2000/2002/2004 datasets.

    Directory layout (standard FVC):
        <year_root>/Dbs/<DbN_a|DbN_b>/<subject>_<impression>.tif

    Metadata:
        identity_id  β€” "<year>_<db>_<subject_id>"  e.g. "2002_db1_042"
                       8 impressions per subject β†’ real quality variation for L_mat
        finger_id    β€” "f01" for all FVC (one finger per subject in competition protocol)
        sensor_id    β€” "fvc<year>_db<N>"  e.g. "fvc2002_db1"
        dataset      β€” "fvc<year>"

    Subsets _a and _b belong to the same sensor_id β€” they are train/test splits
    of the same capture device, not different devices.
    """

    def __init__(self, image_size: int = 224):
        self.transform = transforms.Compose(
            [
                transforms.Resize((image_size, image_size)),
                transforms.ToTensor(),
            ]
        )

    def discover(self, paths: FVCPaths) -> list[dict[str, str]]:
        records: list[dict[str, str]] = []
        year_roots = [
            (paths.root_fvc2000, "2000"),
            (paths.root_fvc2002, "2002"),
            (paths.root_fvc2004, "2004"),
        ]
        for extra in paths.extra_roots:
            year_roots.append((extra, "extra"))
        for root_str, year in year_roots:
            if not root_str:
                continue
            root = Path(root_str)
            dbs_dir = root / "Dbs" if (root / "Dbs").exists() else root
            records.extend(self._scan_dbs(dbs_dir, year))
        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_dbs(self, dbs_root: Path, year: str) -> list[dict[str, str]]:
        if not dbs_root.exists():
            return []
        records: list[dict[str, str]] = []
        for db_dir in sorted(dbs_root.iterdir()):
            if not db_dir.is_dir():
                continue
            db_name = db_dir.name.lower()  # e.g. "db1_a", "DB1_A"
            # Normalise: "db1_a" or "DB1_A" β†’ db_id = "db1"
            db_id = self._parse_db_id(db_name)
            if db_id is None:
                continue
            sensor_id = f"fvc{year}_{db_id}"
            dataset = f"fvc{year}"
            for img_path in sorted(db_dir.iterdir()):
                if not img_path.is_file() or img_path.suffix.lower() not in IMAGE_EXTS:
                    continue
                meta = self._parse_filename(img_path, sensor_id, dataset, year, db_id)
                if meta is not None:
                    records.append(meta)
        return records

    @staticmethod
    def _parse_db_id(db_dir_name: str) -> str | None:
        """'Db1_a', 'DB2_B', 'db3_a' β†’ 'db1', 'db2', 'db3'."""
        name = db_dir_name.lower().strip()
        # Strip trailing subset suffix (_a, _b, _A, _B)
        for suffix in ("_a", "_b"):
            if name.endswith(suffix):
                name = name[: -len(suffix)]
                break
        # Accept names like 'db1', 'db2', 'db3', 'db4'
        if name.startswith("db") and name[2:].isdigit():
            return name
        return None

    @staticmethod
    def _parse_filename(
        img_path: Path,
        sensor_id: str,
        dataset: str,
        year: str,
        db_id: str,
    ) -> dict[str, str] | None:
        """Parse '<subject_id>_<impression_id>.tif' β†’ metadata record."""
        stem = img_path.stem  # e.g. "042_3" or "100_8"
        parts = stem.split("_")
        if len(parts) != 2:
            return None
        subject_str, impression_str = parts
        if not subject_str.isdigit() or not impression_str.isdigit():
            return None

        subject_id = int(subject_str)
        impression_id = int(impression_str)

        # Unique identity key: year + db + subject_id
        identity_id = f"{year}_{db_id}_{subject_id:04d}"

        return {
            "identity_id": identity_id,
            "finger_id": "f01",  # FVC: one finger per subject
            "impression_id": str(impression_id),
            "sensor_id": sensor_id,
            "dataset": dataset,
            "image_path": str(img_path),
        }