File size: 5,716 Bytes
cfc7a54 | 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 | """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
# ---------------------------------------------------------------------------
# Quality features
# ---------------------------------------------------------------------------
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)
# wavelength in pixels: 8–16 px for 500 dpi prints at 224px crops
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)
# Combine: each signal contributes roughly equally after normalisation.
# Raw typical ranges (empirical, 500-dpi fingerprints at 224 px):
# g_energy ~[0.0001, 0.006]
# contrast ~[5, 60]
# lap_var ~[50, 3000]
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)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
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
# --image-dir
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()
|