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

"""Fingerprint-specific image augmentations for V2 pipeline.

Augmentations from the MDGT v2 plan:
    1. Random rotation ±15° (finger placement variation)
    2. Random translation ±10% (off-center capture)
    3. Elastic deformation σ=8, α=60 (skin distortion under pressure)
    4. Random brightness/contrast ±0.2 (sensor / moisture variation)
    5. Random crop + resize 0.8-1.0 (partial fingerprint)
    6. Gaussian noise σ=0.01-0.03 (sensor noise)
    7. CutOut 1-3 patches (occlusion / smudge)
    8. NO horizontal flip (fingerprints are chirally distinct)
"""

import random

import torch
import torch.nn as nn
from torchvision import transforms as T


class GaussianNoise(nn.Module):
    """Add Gaussian noise to a tensor image."""

    def __init__(self, std_min: float = 0.01, std_max: float = 0.03, p: float = 0.5):
        super().__init__()
        self.std_min = std_min
        self.std_max = std_max
        self.p = p

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if random.random() > self.p:
            return x
        std = random.uniform(self.std_min, self.std_max)
        return (x + torch.randn_like(x) * std).clamp(0, 1)


class MultiCutOut(nn.Module):
    """Erase 1-N random rectangular patches (CutOut / occlusion simulation)."""

    def __init__(
        self,
        max_patches: int = 3,
        min_size: int = 16,
        max_size: int = 32,
        p: float = 0.5,
    ):
        super().__init__()
        self.max_patches = max_patches
        self.min_size = min_size
        self.max_size = max_size
        self.p = p

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if random.random() > self.p:
            return x
        _, H, W = x.shape
        n_patches = random.randint(1, self.max_patches)
        for _ in range(n_patches):
            ph = random.randint(self.min_size, self.max_size)
            pw = random.randint(self.min_size, self.max_size)
            y = random.randint(0, max(0, H - ph))
            xc = random.randint(0, max(0, W - pw))
            x[:, y:y + ph, xc:xc + pw] = 0.0
        return x


def build_train_transform(image_size: int = 224, profile: str = "standard") -> T.Compose:
    """Build the training augmentation pipeline.

    Returns a ``torchvision.transforms.Compose`` that takes a PIL image
    and returns a ``(1, H, W)`` tensor normalised to [0, 1].
    """
    if profile not in {"standard", "light"}:
        raise ValueError(f"Unsupported augmentation profile: {profile}")

    if profile == "light":
        geometric = [
            T.Resize((image_size, image_size)),
            T.RandomRotation(degrees=7, fill=255),
            T.RandomAffine(degrees=0, translate=(0.04, 0.04), fill=255),
            T.RandomResizedCrop(
                image_size,
                scale=(0.92, 1.0),
                ratio=(0.98, 1.02),
            ),
        ]
        pixel = [
            T.ColorJitter(brightness=0.1, contrast=0.1),
        ]
        tensor_aug = [
            GaussianNoise(std_min=0.003, std_max=0.012, p=0.25),
            MultiCutOut(max_patches=1, min_size=12, max_size=20, p=0.15),
        ]
    else:
        geometric = [
            T.Resize((image_size, image_size)),
            T.RandomRotation(degrees=15, fill=255),
            T.RandomAffine(degrees=0, translate=(0.1, 0.1), fill=255),
        ]

        try:
            geometric.append(
                T.ElasticTransform(alpha=60.0, sigma=8.0, fill=255)
            )
        except AttributeError:
            pass

        geometric.append(
            T.RandomResizedCrop(image_size, scale=(0.8, 1.0), ratio=(0.95, 1.05)),
        )

        pixel = [
            T.ColorJitter(brightness=0.2, contrast=0.2),
        ]
        tensor_aug = [
            GaussianNoise(std_min=0.01, std_max=0.03, p=0.5),
            MultiCutOut(max_patches=3, min_size=16, max_size=32, p=0.5),
        ]

    to_tensor = [
        T.ToTensor(),
    ]

    return T.Compose(geometric + pixel + to_tensor + tensor_aug)


def build_val_transform(image_size: int = 224) -> T.Compose:
    """Validation transform: resize + to tensor (no augmentation)."""
    return T.Compose([
        T.Resize((image_size, image_size)),
        T.ToTensor(),
    ])