"""Side-by-side stills at several saturation and contrast settings, to be chosen by eye. The user's complaint is that the picture looks washed out and dull. That is not an error problem: every metric in this project scores fidelity *to the source*, the source itself is desaturated, and so a faithful encode is correctly dull. Pushing saturation makes the picture livelier and every error number worse at the same time, which means no measurement here can decide it - only a person looking at the result can. So this renders the same frames at a few settings, each one actually quantised through the encoder's own palette fit, and writes them as labelled strips. What it shows is the real trade: more saturation moves colours into coarser steps of the VDP's 3-bit-per- channel ramp, so past some point the gain in liveliness is paid for in banding. Error against the *adjusted* source is reported too, because that is the number the encoder would then be optimising, and it is worth knowing whether a push makes the frame harder to encode as well as different. python tools/saturation.py fields out/saturation --frames 200,1500,2900,4300 """ from __future__ import annotations import argparse import sys from pathlib import Path import numpy as np from PIL import Image, ImageDraw ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from rrmd.encode import fit_region, load_picture, predict # noqa: E402 LUMA = np.array([0.299, 0.587, 0.114]) SETTINGS = [ ("source", 1.00, 1.00), ("sat 1.2", 1.20, 1.00), ("sat 1.4", 1.40, 1.00), ("sat 1.4 + contrast 1.1", 1.40, 1.10), ("sat 1.7 + contrast 1.15", 1.70, 1.15), ] def adjust(rgb: np.ndarray, saturation: float, contrast: float) -> np.ndarray: """Push saturation about each pixel's own luma, then contrast about mid grey. Saturation is applied in linear 0-255 space around luma rather than in HSV: it keeps the luma the encoder's cost metric weights most, so a push changes colour without moving brightness, and the two knobs stay independent. """ x = rgb.astype(np.float64) grey = (x @ LUMA)[..., None] x = grey + (x - grey) * saturation x = (x - 128.0) * contrast + 128.0 return np.clip(x, 0, 255).astype(np.uint8) def encode_once(rgb: np.ndarray) -> tuple[np.ndarray, float]: """What the ROM would show for this picture, and the error per pixel.""" lines, line_of, shade_of, pens, history = fit_region(rgb) shown = predict(pens, line_of, shade_of, lines) return shown, history[-1] / (rgb.shape[0] * rgb.shape[1]) def strip(frame: int, source: np.ndarray, out: Path, scale: int = 2) -> list[str]: """One row per setting: the adjusted source, then what the ROM would show.""" rows, notes = [], [] for name, sat, con in SETTINGS: adjusted = adjust(source, sat, con) if (sat, con) != (1.0, 1.0) else source shown, err = encode_once(adjusted) rows.append((name, adjusted, shown, err)) notes.append(f"{name}: error/pixel {err:.1f}") h, w, _ = source.shape canvas = Image.new("RGB", (2 * w * scale, len(rows) * h * scale), (16, 16, 16)) for i, (name, adjusted, shown, err) in enumerate(rows): for j, img in enumerate((adjusted, shown)): tile = Image.fromarray(img).resize((w * scale, h * scale), Image.NEAREST) d = ImageDraw.Draw(tile) label = f"{name} {'adjusted source' if j == 0 else 'as the ROM shows it'} err {err:.1f}" d.rectangle([0, 0, 8 * len(label) + 8, 16], fill=(0, 0, 0)) d.text((4, 3), label, fill=(255, 255, 0)) canvas.paste(tile, (j * w * scale, i * h * scale)) out.mkdir(parents=True, exist_ok=True) # out is the directory, not a file in one path = out / f"saturation_f{frame:05d}.png" canvas.save(path) print(f" wrote {path}") return notes def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("fields", type=Path) ap.add_argument("out", type=Path, nargs="?", default=Path("out/saturation")) ap.add_argument("--frames", default="200,1500,2900,4300", help="comma-separated frame numbers (1-based, as the files are named)") # fmt: skip args = ap.parse_args(argv) print("left column: the source after the adjustment. right column: what the ROM would show.") print("error is against the adjusted source, so it is not comparable between rows -") print("a push that looks better will usually read as a worse number.\n") for frame in (int(f) for f in args.frames.split(",")): path = args.fields / f"f{frame:05d}.png" if not path.exists(): print(f" {path} is not there, skipping") continue print(f"frame {frame}:") for note in strip(frame, load_picture(path), args.out): print(f" {note}") print("\nNo measurement decides this one. Pick the row that looks right.") return 0 if __name__ == "__main__": raise SystemExit(main())