| """Generate NFIQ2-proxy quality scores using image heuristics. |
| |
| NFIQ2 is not available as a pip package and requires building from source. |
| This script approximates it using: |
| - Gabor filter energy at fingerprint ridge frequencies (8–16 px/cycle) |
| - Block-wise local contrast (RMS of intensity) |
| - Laplacian variance (sharpness) |
| |
| The three signals are fused and rescaled to [0, 100], matching NFIQ2 convention |
| (higher = better quality). Scores are written as JSONL with the same schema |
| expected by run_eval.py: |
| {"image_path": "...", "q_score": 73.2} |
| |
| Usage (reads image paths from an existing scores file, e.g. sifq_scores.jsonl): |
| python sifq/scripts/gen_nfiq2_proxy_scores.py \ |
| --sifq-scores sifq/eval_results/sifq_scores.jsonl \ |
| --output /tmp/nfiq2_scores.jsonl |
| |
| Or scan a directory directly: |
| python sifq/scripts/gen_nfiq2_proxy_scores.py \ |
| --image-dir dataset/302b/images/baseline \ |
| --output /tmp/nfiq2_scores.jsonl |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| from pathlib import Path |
|
|
| import cv2 |
| import numpy as np |
|
|
|
|
| |
| |
| |
|
|
| def _gabor_energy(gray: np.ndarray, image_size: int = 224) -> float: |
| """Mean Gabor filter energy at typical fingerprint ridge frequencies.""" |
| img = cv2.resize(gray, (image_size, image_size)).astype(np.float32) / 255.0 |
| total = 0.0 |
| count = 0 |
| for theta_deg in range(0, 180, 30): |
| theta = np.deg2rad(theta_deg) |
| |
| for wavelength in (8, 12, 16): |
| sigma = wavelength * 0.56 |
| kern = cv2.getGaborKernel( |
| (31, 31), sigma, theta, wavelength, gamma=0.5, psi=0, |
| ktype=cv2.CV_32F, |
| ) |
| filtered = cv2.filter2D(img, cv2.CV_32F, kern) |
| total += float(np.mean(filtered ** 2)) |
| count += 1 |
| return total / count if count else 0.0 |
|
|
|
|
| def _local_contrast(gray: np.ndarray, block: int = 16) -> float: |
| """Mean RMS contrast over non-overlapping blocks.""" |
| img = cv2.resize(gray, (224, 224)).astype(np.float32) |
| h, w = img.shape |
| vals = [] |
| for r in range(0, h - block + 1, block): |
| for c in range(0, w - block + 1, block): |
| patch = img[r : r + block, c : c + block] |
| vals.append(float(np.std(patch))) |
| return float(np.mean(vals)) if vals else 0.0 |
|
|
|
|
| def _laplacian_var(gray: np.ndarray) -> float: |
| """Variance of Laplacian — sharpness metric.""" |
| img = cv2.resize(gray, (224, 224)) |
| lap = cv2.Laplacian(img, cv2.CV_64F) |
| return float(np.var(lap)) |
|
|
|
|
| def _quality_score(image_path: str) -> float | None: |
| img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) |
| if img is None: |
| return None |
| g_energy = _gabor_energy(img) |
| contrast = _local_contrast(img) |
| lap_var = _laplacian_var(img) |
| |
| |
| |
| |
| |
| score = ( |
| np.clip(g_energy / 0.006, 0.0, 1.0) * 0.40 + |
| np.clip(contrast / 60.0, 0.0, 1.0) * 0.35 + |
| np.clip(lap_var / 3000.0, 0.0, 1.0) * 0.25 |
| ) |
| return round(float(score) * 100.0, 2) |
|
|
|
|
| |
| |
| |
|
|
| def parse_args() -> argparse.Namespace: |
| p = argparse.ArgumentParser(description="Generate NFIQ2-proxy quality scores") |
| src = p.add_mutually_exclusive_group(required=True) |
| src.add_argument( |
| "--sifq-scores", type=str, |
| help="Path to SIFQ scores JSONL; image paths are read from 'image_path' field", |
| ) |
| src.add_argument( |
| "--image-dir", type=str, |
| help="Root directory to scan recursively for .png/.bmp/.wsq images", |
| ) |
| p.add_argument("--output", type=str, default="/tmp/nfiq2_scores.jsonl") |
| p.add_argument( |
| "--extensions", type=str, default="png,bmp,wsq,jpg,jpeg", |
| help="Comma-separated file extensions to scan (only with --image-dir)", |
| ) |
| return p.parse_args() |
|
|
|
|
| def collect_paths(args: argparse.Namespace) -> list[str]: |
| if args.sifq_scores: |
| paths: list[str] = [] |
| with open(args.sifq_scores, encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if line: |
| paths.append(json.loads(line)["image_path"]) |
| return paths |
| |
| exts = {f".{e.lstrip('.')}" for e in args.extensions.split(",")} |
| return [ |
| str(p) for p in Path(args.image_dir).rglob("*") |
| if p.suffix.lower() in exts |
| ] |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| paths = collect_paths(args) |
| print(f"Scoring {len(paths)} images → {args.output}") |
|
|
| out = Path(args.output) |
| out.parent.mkdir(parents=True, exist_ok=True) |
|
|
| skipped = 0 |
| with out.open("w", encoding="utf-8") as fout: |
| for i, p in enumerate(paths): |
| score = _quality_score(p) |
| if score is None: |
| skipped += 1 |
| continue |
| fout.write(json.dumps({"image_path": p, "q_score": score}) + "\n") |
| if (i + 1) % 1000 == 0: |
| print(f" {i + 1}/{len(paths)} (skipped={skipped})") |
|
|
| print(f"Done. Written {len(paths) - skipped} records, skipped {skipped}.") |
| print(f"Output: {out}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|