wenjieshu's picture
Add files using upload-large-folder tool
b8ea052 verified
Raw History Blame Contribute Delete
2.9 kB
"""Quality gate checkers."""
from __future__ import annotations
from pathlib import Path
import numpy as np
from PIL import Image
from pvr_eval.core.schema import QualityGateResult
def image_quality_gate(pred_image: str | Path) -> QualityGateResult:
path = Path(pred_image)
if not path.is_file():
return QualityGateResult(status="fail", score=0.0, evidence={"reason": "missing_prediction", "path": str(path)})
try:
with Image.open(path) as image:
width, height = image.size
mode = image.mode
image.verify()
# PIL requires verify() to be called immediately after open; reopen
# for pixel statistics rather than mutating the verified handle first.
with Image.open(path) as image:
rgba = np.asarray(image.convert("RGBA").resize((min(width, 256), min(height, 256))))
except Exception as exc: # pragma: no cover - PIL exception details vary.
return QualityGateResult(status="fail", score=0.0, evidence={"reason": "invalid_image", "error": str(exc)})
if width < 16 or height < 16:
return QualityGateResult(
status="fail",
score=0.0,
evidence={"reason": "image_too_small", "width": width, "height": height, "mode": mode},
)
alpha = rgba[:, :, 3]
rgb = rgba[:, :, :3].astype(np.float32)
luminance = 0.2126 * rgb[:, :, 0] + 0.7152 * rgb[:, :, 1] + 0.0722 * rgb[:, :, 2]
mean_luminance = float(luminance.mean())
visible_fraction = float((alpha >= 8).mean())
channel_std = float(rgb.std())
luminance_range = float(np.percentile(luminance, 99) - np.percentile(luminance, 1))
quantized = (rgb // 16).astype(np.uint8).reshape(-1, 3)
unique_colors = int(len(np.unique(quantized, axis=0)))
evidence = {
"width": width,
"height": height,
"mode": mode,
"visible_fraction": round(visible_fraction, 6),
"channel_std": round(channel_std, 6),
"mean_luminance": round(mean_luminance, 6),
"luminance_p01_p99_range": round(luminance_range, 6),
"quantized_unique_colors": unique_colors,
"semantic_unrelated_check": "not_claimed_by_pixel_quality_gate",
}
if visible_fraction < 0.05:
return QualityGateResult(status="fail", score=0.0, evidence={"reason": "mostly_transparent_image", **evidence})
# Tiny uniform images are common unit-test/parser fixtures. The formal
# PVR predictions are full-resolution; apply the semantic blank gate only
# where the image is large enough for that inference to be meaningful.
if width * height >= 65536 and channel_std < 1.5 and luminance_range < 8.0 and unique_colors < 4:
return QualityGateResult(status="fail", score=0.0, evidence={"reason": "near_blank_or_solid_image", **evidence})
return QualityGateResult(status="pass", score=1.0, evidence=evidence)