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

from dataclasses import dataclass

import cv2
import numpy as np


@dataclass(frozen=True)
class DegradationSpec:
    deg_type: str
    level: int


class DrySkinSimulator:
    """Simulate dry skin by reducing local contrast and introducing cracks."""

    def __init__(self, severity: int):
        self.severity = max(0, int(severity))

    def __call__(self, image: np.ndarray) -> np.ndarray:
        if self.severity <= 0:
            return image
        img = image.astype(np.float32)
        alpha = max(0.4, 1.0 - 0.15 * self.severity)
        beta = 5.0 * self.severity
        img = img * alpha + beta

        h, w = img.shape[:2]
        crack_mask = np.zeros((h, w), dtype=np.float32)
        n_lines = 8 * self.severity
        rng = np.random.default_rng(self.severity)
        for _ in range(n_lines):
            x1, y1 = int(rng.integers(0, w)), int(rng.integers(0, h))
            x2, y2 = int(rng.integers(0, w)), int(rng.integers(0, h))
            cv2.line(crack_mask, (x1, y1), (x2, y2), color=1.0, thickness=1)
        img = img - crack_mask * (12.0 + 4.0 * self.severity)
        return np.clip(img, 0, 255).astype(np.uint8)


class MorphologicalDilator:
    """Simulate wet press by ridge thickening + slight blur.

    T18 fix: use cv2.erode (not dilate) because NIST fingerprints have DARK
    ridges on a LIGHT background.  cv2.erode expands dark regions β†’ ridges
    thicken and bleed into valleys, reducing ridge-valley clarity and
    minutiae reliability β€” exactly the wet-press artefact we want to model.
    The previous cv2.dilate expanded LIGHT areas (valleys), which shrank
    ridges and paradoxically increased apparent clarity.
    """

    def __init__(self, iterations: int):
        self.iterations = max(0, int(iterations))

    def __call__(self, image: np.ndarray) -> np.ndarray:
        if self.iterations <= 0:
            return image
        # T18: erode expands dark ridges (wet smear) instead of dilate.
        # T38 fix: scale kernel size with iterations so that even level 1
        # produces enough ridge thickening to genuinely impair minutiae
        # detectability. The old fixed 3Γ—3 kernel at level 1 was too subtle
        # (~1 px expansion) β€” model saw it as "good ink" not degradation.
        # At 500 DPI ridges are ~25 px wide; we need several px expansion to
        # start merging bifurcations and ridge endings.
        # level 1: 5Γ—5 + sigma=1.8  β†’ visibly thicker ridges, bifurcations blur
        # level 2: 7Γ—7 + sigma=2.6  β†’ ridges start merging at crossings
        # level 3: 9Γ—9 + sigma=3.4  β†’ heavy ridge bleeding, minutiae indistinct
        ks = 3 + 2 * self.iterations          # 5, 7, 9 for levels 1, 2, 3
        sigma = 1.0 + 0.8 * self.iterations   # 1.8, 2.6, 3.4
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ks, ks))
        out = cv2.erode(image, kernel, iterations=1)  # 1 pass, larger kernel
        out = cv2.GaussianBlur(out, (ks, ks), sigmaX=sigma)
        return out


class DegradationPipeline:
    """Controlled degradation augmentation used by L_deg."""

    LEVELS = [0, 1, 2, 3]

    def apply(self, image: np.ndarray, deg_type: str, level: int) -> np.ndarray:
        level = int(level)
        if level <= 0:
            return image.copy()

        if deg_type == "blur":
            k = int(0.5 + level * 0.83) * 2 + 1
            return cv2.GaussianBlur(image, (k, k), sigmaX=0)

        if deg_type == "noise":
            sigma = 5.0 + level * 8.3
            noise = np.random.normal(0.0, sigma, image.shape)
            return np.clip(image.astype(np.float32) + noise, 0, 255).astype(np.uint8)

        if deg_type == "jpeg":
            quality = max(5, 90 - int(level * 25))
            ok, enc = cv2.imencode(
                ".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), quality]
            )
            if not ok:
                return image.copy()
            return cv2.imdecode(enc, cv2.IMREAD_GRAYSCALE)

        if deg_type == "occlusion":
            # T38 fix: revert coverage to paper range 10%–40%.
            # T26 pushed level 3 to 55% but paper (sec 4.4) says 10–40%.
            # 0.133 * level: level1=13%, level2=27%, level3=40%.
            # Eval determinism (T38b: np.random.seed(level)) makes the
            # coverage sweep coherent without needing extra signal.
            out = image.copy()
            h, w = out.shape[:2]
            block = int(min(h, w) * 0.133 * level)  # level3 β†’ 40% (paper range)
            block = max(1, block)
            x = np.random.randint(0, max(1, w - block + 1))
            y = np.random.randint(0, max(1, h - block + 1))
            out[y : y + block, x : x + block] = 255
            return out

        if deg_type == "dry_skin":
            return DrySkinSimulator(severity=level)(image)

        if deg_type == "wet_press":
            return MorphologicalDilator(iterations=level)(image)

        raise ValueError(f"Unsupported degradation type: {deg_type}")