playful / chess-sim /code /sim /camera_effects.py
Ali-Uraish's picture
Add files using upload-large-folder tool
fad6045 verified
Raw History Blame Contribute Delete
4.87 kB
"""How a cheap webcam renders the scene: auto-exposure, white balance, exposure, gamma, contrast,
saturation, vignetting, blur, sensor noise and JPEG compression (UVC webcams stream
MJPEG). Parameters are drawn per camera per episode from [webcam] in
phase2_config.toml; the noise is drawn per frame. Auto-exposure sets one gain per
episode from the first frame (mean brightness to a drawn target), as a webcam settles
on a scene; the exposure jitter then over- or under-exposes around it. Applied to the rendered image
before the red and blue squares, which are drawn on the captured frame. The policy
evaluation in simulation uses the same code, so it sees what training saw.
"""
from __future__ import annotations
import io
from dataclasses import dataclass
import numpy as np
from PIL import Image, ImageFilter
LUMA = np.array([0.299, 0.587, 0.114], np.float32)
@dataclass
class WebcamLook:
white_balance: np.ndarray # per-channel gain
exposure: float
gamma: float
contrast: float
saturation: float
vignette: float
blur_px: float
noise: float
jpeg_quality: int
target: float = 0.45 # auto-exposure target mean brightness
gain: float | None = None # set from the first frame
_vignette_mask: np.ndarray | None = None
@classmethod
def sample(cls, rng: np.random.Generator, cfg: dict) -> "WebcamLook":
c = cfg["webcam"]
u = lambda key: float(rng.uniform(*c[key]))
return cls(white_balance=(1 + rng.uniform(-c["white_balance"], c["white_balance"], 3)).astype(np.float32),
exposure=u("exposure"), gamma=u("gamma"), contrast=u("contrast"), saturation=u("saturation"),
vignette=u("vignette"), blur_px=u("blur_px"), noise=u("noise"),
jpeg_quality=int(rng.integers(c["jpeg_quality"][0], c["jpeg_quality"][1] + 1)),
target=u("auto_exposure_target"))
def describe(self) -> dict:
return dict(white_balance=[round(float(x), 3) for x in self.white_balance], exposure=round(self.exposure, 3),
auto_gain=None if self.gain is None else round(self.gain, 3),
gamma=round(self.gamma, 3), blur_px=round(self.blur_px, 2), noise=round(self.noise, 4),
jpeg_quality=self.jpeg_quality)
def apply(self, image: np.ndarray, rng: np.random.Generator) -> np.ndarray:
h, w = image.shape[:2]
x = image.astype(np.float32) / 255
if self.gain is None:
self.gain = float(np.clip(self.target / max(float((x @ LUMA).mean()), 1e-3), 0.6, 3.5))
x = np.clip(x * (self.white_balance * (self.gain * self.exposure)), 0, 1) ** self.gamma
mean = float(x.mean())
x = (x - mean) * self.contrast + mean
grey = (x @ LUMA)[..., None]
x = grey + (x - grey) * self.saturation
if self.vignette > 0:
if self._vignette_mask is None:
yy, xx = np.ogrid[:h, :w]
r2 = ((xx - w / 2) / (w / 2)) ** 2 + ((yy - h / 2) / (h / 2)) ** 2
self._vignette_mask = (1 - self.vignette * np.clip(r2 / 2, 0, 1)).astype(np.float32)[..., None]
x *= self._vignette_mask
if self.noise > 0:
x += rng.standard_normal(x.shape, dtype=np.float32) * self.noise
img = Image.fromarray((np.clip(x, 0, 1) * 255 + 0.5).astype(np.uint8))
if self.blur_px > 0.05:
img = img.filter(ImageFilter.GaussianBlur(self.blur_px))
buf = io.BytesIO()
img.save(buf, "JPEG", quality=self.jpeg_quality)
buf.seek(0)
return np.asarray(Image.open(buf).convert("RGB"))
def training_look(image: np.ndarray, crf: int = 30, pix_fmt: str = "yuv420p") -> np.ndarray:
"""The frame as the policy saw it in training: one pass through the dataset's video
codec (H.264; LeRobot's default is 4:2:0 chroma at CRF 30, [dataset] video_crf and
video_pix_fmt override it). Chroma subsampling washes out the small red and blue
squares, and a policy trained on decoded video looks for them in that form, so every
live frame (sim test or real camera) goes through the same round trip before the
policy sees it."""
import av
buf = io.BytesIO()
with av.open(buf, "w", format="mp4") as container:
stream = container.add_stream("libx264", rate=30)
stream.width, stream.height = image.shape[1], image.shape[0]
stream.pix_fmt = pix_fmt
stream.options = {"crf": str(crf), "g": "2", "threads": "1"}
for packet in stream.encode(av.VideoFrame.from_ndarray(np.ascontiguousarray(image), format="rgb24")):
container.mux(packet)
for packet in stream.encode():
container.mux(packet)
buf.seek(0)
with av.open(buf) as container:
return next(container.decode(video=0)).to_ndarray(format="rgb24")