File size: 10,508 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
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"),
    )