hybrid-isp / isp /analysis.py
Vkun05's picture
Deploy hybrid ISP app
0568fac verified
Raw History Blame Contribute Delete
9.54 kB
"""Image analyser + adaptive router: decides how much of the network each photo needs, and why."""
from __future__ import annotations
import json
import os
from dataclasses import asdict, dataclass, field, fields
from pathlib import Path
import cv2
import numpy as np
from isp.classical.denoise import estimate_sigma
from isp.classical.sharpen import noise_aware_amount
from isp.classical.wb import angular_error_deg, estimator_spread, shades_of_gray
from isp.raw import RawImage, pack
TARGET_MEAN = 0.16 # linear mean green of a well-exposed scene
MAX_GAIN = 16.0
CONFIG_PATH = Path(os.environ.get("ISP_ROUTER_CONFIG", Path(__file__).with_name("router_config.json")))
@dataclass
class RouterConfig:
"""Router thresholds. Tuned on the VALIDATION scene only (eval/tune_router.py writes router_config.json)."""
wb_angle_lo: float = 5.0 # as-shot WB trusted fully below this disagreement with shades-of-gray (degrees)
wb_angle_hi: float = 15.0 # ... and replaced fully above this
wb_spread_max: float = 4.0 # if gray-world / shades-of-gray / gray-edge disagree by more, keep as-shot
fast_sigma: float = 0.004 # visible noise below this -> fast classical path (network skipped)
high_sigma: float = 0.03 # above this -> learned core + chroma-only cleanup
sharpen_k: float = 0.5 # sharpening = k / (1 + sigma / sharpen_sigma0)
sharpen_sigma0: float = 0.01
ev_threshold: float = 0.6 # under-exposure (stops) before digital gain is applied
local_tone_dr: float = 12.0 # dynamic range (stops) that triggers local tone mapping
residual_k: float = 2.0 # network may change a pixel by at most k * sigma(x) of the noise model (0 = off)
tuned_on: str = "defaults (not tuned)"
def load_config(path: Path = CONFIG_PATH) -> RouterConfig:
try:
raw = json.loads(Path(path).read_text(encoding="utf-8"))
except FileNotFoundError:
return RouterConfig()
known = {f.name for f in fields(RouterConfig)}
return RouterConfig(**{k: v for k, v in raw.items() if k in known})
CONFIG = load_config()
@dataclass
class Analysis:
sigma: float # noise std (normalised RAW units, before any gain)
ev: float # exposure offset vs a well-exposed scene, in stops
clipped: float # fraction of clipped pixels
wb_conf: float # 0..1 trust in the as-shot white balance
wb_angle: float | None
dynamic_range: float # stops (p99.5 / p0.5 of smoothed luma)
mean_level: float
wb_spread: float = 0.0 # disagreement between independent WB estimators (degrees)
def as_dict(self) -> dict:
return {k: (round(v, 5) if isinstance(v, float) else v) for k, v in asdict(self).items()}
@dataclass
class Route:
path: str # "fast" | "learned" | "learned_chroma"
label: str
gain: float
wb_method: str
wb_gains: tuple[float, float, float]
local_tone: bool
sharpen: float
chroma: float
sigma_eff: float
forced: bool = False
reasons: list[str] = field(default_factory=list)
def as_dict(self) -> dict:
d = asdict(self)
d["wb_gains"] = [round(g, 4) for g in self.wb_gains]
for k in ("gain", "sharpen", "chroma", "sigma_eff"):
d[k] = round(d[k], 5)
return d
def analyze(raw: RawImage) -> Analysis:
q = pack(raw.bayer)
g = 0.5 * (q[..., 1] + q[..., 2])
sigma = estimate_sigma(q[..., 1])
mean_g = float(g.mean()) * raw.exposure # relative to the scene's baseline exposure
# Under-exposure = how much more gain the same highlight-aware AE used for the scene would add now.
needed = auto_exposure(raw.bayer * raw.exposure)
ev = float(-np.log2(needed)) if needed > 1.0 else float(max(np.log2(max(mean_g, 1e-6) / TARGET_MEAN), 0.0))
clipped = float((q.max(axis=-1) >= 0.98).mean())
sog = shades_of_gray(raw.bayer)
spread = estimator_spread(raw.bayer)
if raw.wb_gains is not None:
angle = angular_error_deg(raw.wb_gains, sog)
span = max(CONFIG.wb_angle_hi - CONFIG.wb_angle_lo, 1e-6)
wb_conf = float(np.clip(1.0 - (angle - CONFIG.wb_angle_lo) / span, 0.0, 1.0))
if spread > CONFIG.wb_spread_max: # coloured scene: the estimators are unreliable, the camera is not
wb_conf = 1.0
else:
angle, wb_conf = None, 0.0
small = cv2.resize(g, (max(1, g.shape[1] // 4), max(1, g.shape[0] // 4)), interpolation=cv2.INTER_AREA)
lo, hi = np.maximum(np.percentile(small, [0.5, 99.5]), 0.0) # RAW keeps negative noise values
# Measurable dynamic range stops at the noise floor (noise std after 4x4 averaging = sigma/4).
lo = max(lo, 3.0 * sigma / 4.0, 1e-4)
dr = float(np.log2(max(hi, lo) / lo))
return Analysis(sigma=sigma, ev=ev, clipped=clipped, wb_conf=wb_conf, wb_angle=angle,
dynamic_range=dr, mean_level=mean_g, wb_spread=spread)
def auto_exposure(bayer: np.ndarray, target: float = 0.14) -> float:
"""Scene baseline exposure for real RAW (what a camera's AE would pick): bring the mean green to
`target` without pushing more than ~1% of pixels past white. Statistics come from 4x4-binned
green, so sensor noise does not inflate the highlight percentile. Clamped to [1, 16]."""
q = pack(bayer)
g = 0.5 * (q[..., 1] + q[..., 2])
small = cv2.resize(g, (max(1, g.shape[1] // 4), max(1, g.shape[0] // 4)), interpolation=cv2.INTER_AREA)
small = np.maximum(small, 0)
mean, p99 = float(small.mean()), float(np.percentile(small, 99))
e = min(target / max(mean, 1e-5), 1.0 / max(p99, 1e-5))
return float(np.clip(e, 1.0, 16.0))
def _blend_gains(a, b, w: float) -> tuple[float, float, float]:
"""Blend two WB estimates in illuminant space (w = weight of a)."""
ia, ib = 1.0 / np.asarray(a, np.float64), 1.0 / np.asarray(b, np.float64)
ia, ib = ia / ia[1], ib / ib[1]
ill = w * ia + (1 - w) * ib
return (float(ill[1] / ill[0]), 1.0, float(ill[1] / ill[2]))
def decide(raw: RawImage, a: Analysis, force_path: str | None = None) -> Route:
reasons: list[str] = []
# Exposure
cfg = CONFIG
if a.ev < -cfg.ev_threshold:
gain = float(min(2.0 ** (-a.ev), MAX_GAIN)) # = the scene AE's extra gain
reasons.append(f"Under-exposed by {-a.ev:.1f} EV -> digital gain x{gain:.1f} before the network (noise map scaled to match).")
else:
gain = 1.0
reasons.append(f"Exposure OK ({a.ev:+.1f} EV) -> no gain.")
# White balance
sog = shades_of_gray(raw.bayer)
if raw.wb_gains is None:
wb_method, wb_gains = "shades-of-gray", sog
reasons.append("No white-balance metadata -> shades-of-gray estimate (p=6).")
elif a.wb_spread > CONFIG.wb_spread_max and a.wb_angle is not None and a.wb_angle > CONFIG.wb_angle_lo:
wb_method, wb_gains = "as-shot", raw.wb_gains
reasons.append(f"Scene colours are not neutral (WB estimators disagree by {a.wb_spread:.1f} deg) -> "
f"trust the camera's as-shot white balance.")
elif a.wb_conf >= 0.999:
wb_method, wb_gains = "as-shot", raw.wb_gains
reasons.append(f"As-shot white balance agrees with the scene ({a.wb_angle:.1f} deg) -> keep it.")
elif a.wb_conf <= 0.001:
wb_method, wb_gains = "shades-of-gray", sog
reasons.append(f"As-shot white balance disagrees with the scene by {a.wb_angle:.1f} deg -> replaced by shades-of-gray.")
else:
wb_method, wb_gains = "blend", _blend_gains(raw.wb_gains, sog, a.wb_conf)
reasons.append(f"As-shot white balance is uncertain ({a.wb_angle:.1f} deg off) -> blended {a.wb_conf:.0%} as-shot / shades-of-gray.")
# Noise -> path (noise as it will be seen: after the router gain and the scene's baseline exposure)
sigma_eff = a.sigma * gain * raw.exposure
if force_path:
path, forced = force_path, True
reasons.append(f"Router override: path forced to '{force_path}'.")
elif sigma_eff < cfg.fast_sigma:
path, forced = "fast", False
reasons.append(f"Noise sigma={sigma_eff:.4f} < {cfg.fast_sigma} -> fast classical path (network skipped).")
elif sigma_eff < cfg.high_sigma:
path, forced = "learned", False
reasons.append(f"Noise sigma={sigma_eff:.4f} -> learned core.")
else:
path, forced = "learned_chroma", False
reasons.append(f"High noise sigma={sigma_eff:.4f} >= {cfg.high_sigma} -> learned core + chroma-only cleanup, weaker sharpening.")
chroma = float(np.clip((sigma_eff - cfg.high_sigma) / cfg.high_sigma + 0.5, 0.0, 1.0)) if path == "learned_chroma" else 0.0
sharpen = noise_aware_amount(sigma_eff, cfg.sharpen_k, cfg.sharpen_sigma0)
reasons.append(f"Sharpening = {cfg.sharpen_k:g} / (1 + sigma/{cfg.sharpen_sigma0:g}) = {sharpen:.2f}.")
local = a.dynamic_range > cfg.local_tone_dr and gain < 4
if local:
reasons.append(f"High dynamic range ({a.dynamic_range:.1f} stops) -> local tone mapping.")
labels = {"fast": "Fast classical path", "learned": "Learned core", "learned_chroma": "Learned core + chroma cleanup"}
return Route(path=path, label=labels.get(path, path), gain=gain, wb_method=wb_method, wb_gains=wb_gains,
local_tone=local, sharpen=sharpen, chroma=chroma, sigma_eff=sigma_eff, forced=forced, reasons=reasons)