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}")