"""Small image metrics that do not require GPU model dependencies.""" from __future__ import annotations from pathlib import Path from typing import Any import numpy as np from PIL import Image def open_rgb(path: str | Path) -> Image.Image: return Image.open(path).convert("RGB") def validate_image(path: str | Path) -> dict[str, Any]: image_path = Path(path) if not image_path.is_file(): return { "ok": False, "failure_stage": "format", "error": "missing_image", "message": f"Image does not exist: {image_path}", } try: image = open_rgb(image_path) except Exception as exc: return { "ok": False, "failure_stage": "format", "error": type(exc).__name__, "message": str(exc), } arr = np.asarray(image) channel_std = float(arr.std()) return { "ok": channel_std >= 1.0, "failure_stage": None if channel_std >= 1.0 else "format", "error": None if channel_std >= 1.0 else "near_blank_image", "width": image.width, "height": image.height, "mode": image.mode, "pixel_std": channel_std, } def load_mask(path: str | Path, size: tuple[int, int]) -> np.ndarray: mask = Image.open(path).convert("L") if mask.size != size: mask = mask.resize(size, Image.Resampling.NEAREST) arr = np.asarray(mask) return arr > 127 def masked_rgb_metrics(input_image: str | Path, pred_image: str | Path, mask_path: str | Path) -> dict[str, Any]: """Compute simple masked RGB preservation metrics. This is deliberately lightweight. Later GPU adapters can add LPIPS/DINO while preserving this output contract. """ input_pil = open_rgb(input_image) pred_pil = open_rgb(pred_image) if pred_pil.size != input_pil.size: pred_pil = pred_pil.resize(input_pil.size, Image.Resampling.BICUBIC) mask = load_mask(mask_path, input_pil.size) mask_area = int(mask.sum()) if mask_area == 0: return { "available": False, "reason": "empty_mask", "score": None, } input_arr = np.asarray(input_pil).astype(np.float32) pred_arr = np.asarray(pred_pil).astype(np.float32) diff = np.abs(input_arr - pred_arr) masked_diff = diff[mask] mae = float(masked_diff.mean() / 255.0) rmse = float(np.sqrt(((masked_diff / 255.0) ** 2).mean())) score = max(0.0, min(1.0, 1.0 - mae * 2.0)) return { "available": True, "mask_area": mask_area, "mae": mae, "rmse": rmse, "score": score, "metric": "masked_rgb_mae", }