Add camera quality control and debug dense stereo
This commit is contained in:
parent
41295fe45f
commit
bd28491b42
8 changed files with 523 additions and 37 deletions
|
|
@ -12,6 +12,15 @@ from .core import (
|
|||
load_fusion_config,
|
||||
)
|
||||
from .render_bridge import RenderBridgeConfig, RenderFramePacket, RenderPointPacket, lower_points_to_render_frame
|
||||
from .camera_control import (
|
||||
AdaptiveCameraController,
|
||||
CameraControlCommand,
|
||||
CameraControlState,
|
||||
CameraQualityTarget,
|
||||
FrameQuality,
|
||||
measure_frame_quality,
|
||||
)
|
||||
from .dense_stereo import DenseStereoConfig, dense_stereo_points
|
||||
from .audio_overlay import AudioVisualSyncStatus, overlay_audio_events
|
||||
from .media_artifacts import RemoteVideoArtifact, remote_video_artifact_for_present_time
|
||||
from .cultcache_docs import (
|
||||
|
|
@ -37,6 +46,12 @@ __all__ = [
|
|||
"RenderBridgeConfig",
|
||||
"RenderFramePacket",
|
||||
"RenderPointPacket",
|
||||
"AdaptiveCameraController",
|
||||
"CameraControlCommand",
|
||||
"CameraControlState",
|
||||
"CameraQualityTarget",
|
||||
"DenseStereoConfig",
|
||||
"FrameQuality",
|
||||
"AudioVisualSyncStatus",
|
||||
"RemoteVideoArtifact",
|
||||
"LIVE_RENDER_FRAME_KEY",
|
||||
|
|
@ -49,6 +64,8 @@ __all__ = [
|
|||
"get_live_render_frame",
|
||||
"lower_frame_to_screen_brushes",
|
||||
"lower_points_to_render_frame",
|
||||
"dense_stereo_points",
|
||||
"measure_frame_quality",
|
||||
"overlay_audio_events",
|
||||
"remote_video_artifact_for_present_time",
|
||||
"put_live_render_frame",
|
||||
|
|
|
|||
154
localcast/sensor_fusion/camera_control.py
Normal file
154
localcast/sensor_fusion/camera_control.py
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FrameQuality:
|
||||
mean_luma: float
|
||||
dark_clip: float
|
||||
bright_clip: float
|
||||
contrast: float
|
||||
sharpness: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraControlState:
|
||||
exposure: float = 0.5
|
||||
gain: float = 0.25
|
||||
focus: float = 0.5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraControlCommand:
|
||||
exposure: float | None = None
|
||||
gain: float | None = None
|
||||
focus: float | None = None
|
||||
|
||||
@property
|
||||
def changed(self) -> bool:
|
||||
return self.exposure is not None or self.gain is not None or self.focus is not None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraQualityTarget:
|
||||
mean_luma: float = 0.52
|
||||
luma_deadband: float = 0.045
|
||||
max_bright_clip: float = 0.015
|
||||
max_dark_clip: float = 0.035
|
||||
min_sharpness: float = 0.035
|
||||
exposure_step: float = 0.035
|
||||
gain_step: float = 0.025
|
||||
focus_step: float = 0.020
|
||||
|
||||
|
||||
class CameraSettingPort(Protocol):
|
||||
def apply(self, command: CameraControlCommand) -> None:
|
||||
...
|
||||
|
||||
|
||||
def measure_frame_quality(frame_bgr: np.ndarray) -> FrameQuality:
|
||||
if frame_bgr.ndim != 3 or frame_bgr.shape[2] != 3:
|
||||
raise ValueError("frame_bgr must have shape HxWx3")
|
||||
frame = frame_bgr.astype(np.float32) / 255.0
|
||||
luma = 0.0722 * frame[:, :, 0] + 0.7152 * frame[:, :, 1] + 0.2126 * frame[:, :, 2]
|
||||
gx = np.diff(luma, axis=1)
|
||||
gy = np.diff(luma, axis=0)
|
||||
sharpness = float(np.mean(np.abs(gx)) + np.mean(np.abs(gy)))
|
||||
return FrameQuality(
|
||||
mean_luma=float(np.mean(luma)),
|
||||
dark_clip=float(np.mean(luma < 0.025)),
|
||||
bright_clip=float(np.mean(luma > 0.975)),
|
||||
contrast=float(np.percentile(luma, 95) - np.percentile(luma, 5)),
|
||||
sharpness=sharpness,
|
||||
)
|
||||
|
||||
|
||||
class AdaptiveCameraController:
|
||||
"""Small bounded controller for manual capture settings.
|
||||
|
||||
The controller owns measurement quality policy. It deliberately emits
|
||||
normalized commands; the driver adapter owns mapping those commands to
|
||||
OpenCV, DirectShow, vendor tools, or a no-op mock in tests.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
state: CameraControlState | None = None,
|
||||
target: CameraQualityTarget | None = None,
|
||||
) -> None:
|
||||
self.state = state or CameraControlState()
|
||||
self.target = target or CameraQualityTarget()
|
||||
self._focus_direction = 1.0
|
||||
|
||||
def update(self, quality: FrameQuality) -> CameraControlCommand:
|
||||
exposure = self.state.exposure
|
||||
gain = self.state.gain
|
||||
focus = self.state.focus
|
||||
|
||||
too_bright = quality.mean_luma > self.target.mean_luma + self.target.luma_deadband
|
||||
too_dark = quality.mean_luma < self.target.mean_luma - self.target.luma_deadband
|
||||
|
||||
if too_bright or quality.bright_clip > self.target.max_bright_clip:
|
||||
exposure -= self.target.exposure_step
|
||||
if quality.bright_clip > self.target.max_bright_clip * 2.0:
|
||||
gain -= self.target.gain_step
|
||||
elif too_dark or quality.dark_clip > self.target.max_dark_clip:
|
||||
exposure += self.target.exposure_step
|
||||
if exposure >= 0.92:
|
||||
gain += self.target.gain_step
|
||||
|
||||
if quality.sharpness < self.target.min_sharpness:
|
||||
focus += self._focus_direction * self.target.focus_step
|
||||
if focus <= 0.05 or focus >= 0.95:
|
||||
self._focus_direction *= -1.0
|
||||
|
||||
exposure = _clamp01(exposure)
|
||||
gain = _clamp01(gain)
|
||||
focus = _clamp01(focus)
|
||||
|
||||
command = CameraControlCommand(
|
||||
exposure=None if abs(exposure - self.state.exposure) < 1e-9 else exposure,
|
||||
gain=None if abs(gain - self.state.gain) < 1e-9 else gain,
|
||||
focus=None if abs(focus - self.state.focus) < 1e-9 else focus,
|
||||
)
|
||||
self.state = CameraControlState(exposure=exposure, gain=gain, focus=focus)
|
||||
return command
|
||||
|
||||
|
||||
class OpenCvCameraSettingPort:
|
||||
def __init__(self, capture: object) -> None:
|
||||
self.capture = capture
|
||||
|
||||
def apply(self, command: CameraControlCommand) -> None:
|
||||
if not command.changed:
|
||||
return
|
||||
import cv2
|
||||
|
||||
# Disable auto controls where OpenCV exposes the knobs, then apply a
|
||||
# normalized manual target. Driver backends differ; failed sets are
|
||||
# non-fatal because image quality feedback will continue next frame.
|
||||
try:
|
||||
self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25)
|
||||
except Exception:
|
||||
pass
|
||||
if command.exposure is not None:
|
||||
_try_set(self.capture, cv2.CAP_PROP_EXPOSURE, -13.0 + command.exposure * 12.0)
|
||||
if command.gain is not None:
|
||||
_try_set(self.capture, cv2.CAP_PROP_GAIN, command.gain * 255.0)
|
||||
if command.focus is not None and hasattr(cv2, "CAP_PROP_FOCUS"):
|
||||
_try_set(self.capture, cv2.CAP_PROP_FOCUS, command.focus * 255.0)
|
||||
|
||||
|
||||
def _try_set(capture: object, prop: int, value: float) -> None:
|
||||
try:
|
||||
capture.set(prop, float(value))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _clamp01(value: float) -> float:
|
||||
return max(0.0, min(1.0, float(value)))
|
||||
126
localcast/sensor_fusion/dense_stereo.py
Normal file
126
localcast/sensor_fusion/dense_stereo.py
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import CameraModel, triangulate_dlt
|
||||
from .render_bridge import RenderPointPacket
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DenseStereoConfig:
|
||||
sample_step: int = 4
|
||||
block_radius: int = 3
|
||||
max_disparity_px: int = 96
|
||||
min_texture: float = 0.020
|
||||
min_ncc: float = 0.72
|
||||
max_reprojection_error_px: float = 6.0
|
||||
radius_m: float = 0.006
|
||||
|
||||
|
||||
def dense_stereo_points(
|
||||
*,
|
||||
prefix: str,
|
||||
left_frame_bgr: np.ndarray,
|
||||
right_frame_bgr: np.ndarray,
|
||||
left_camera: CameraModel,
|
||||
right_camera: CameraModel,
|
||||
timestamp_ns: int,
|
||||
config: DenseStereoConfig | None = None,
|
||||
) -> tuple[RenderPointPacket, ...]:
|
||||
"""Match textured pixels in a calibrated pair and emit RGB surface claims."""
|
||||
|
||||
cfg = config or DenseStereoConfig()
|
||||
left = _luma(left_frame_bgr)
|
||||
right = _luma(right_frame_bgr)
|
||||
height = min(left.shape[0], right.shape[0], left_camera.height, right_camera.height)
|
||||
width = min(left.shape[1], right.shape[1], left_camera.width, right_camera.width)
|
||||
radius = max(1, int(cfg.block_radius))
|
||||
step = max(1, int(cfg.sample_step))
|
||||
points: list[RenderPointPacket] = []
|
||||
|
||||
for row in range(radius, height - radius, step):
|
||||
for col in range(radius + 1, width - radius, step):
|
||||
patch = _patch(left, row, col, radius)
|
||||
texture = float(np.std(patch))
|
||||
if texture < cfg.min_texture:
|
||||
continue
|
||||
best_col, score = _best_horizontal_match(
|
||||
patch,
|
||||
right,
|
||||
row,
|
||||
col,
|
||||
radius,
|
||||
max_disparity_px=cfg.max_disparity_px,
|
||||
)
|
||||
if best_col is None or score < cfg.min_ncc:
|
||||
continue
|
||||
uv_left = np.array([float(col), float(row)], dtype=np.float64)
|
||||
uv_right = np.array([float(best_col), float(row)], dtype=np.float64)
|
||||
try:
|
||||
xyz = triangulate_dlt(left_camera.projection_matrix, uv_left, right_camera.projection_matrix, uv_right)
|
||||
except ValueError:
|
||||
continue
|
||||
if not np.all(np.isfinite(xyz)):
|
||||
continue
|
||||
error = 0.5 * (
|
||||
left_camera.reprojection_error(xyz, uv_left) + right_camera.reprojection_error(xyz, uv_right)
|
||||
)
|
||||
if error > cfg.max_reprojection_error_px:
|
||||
continue
|
||||
b, g, r = (left_frame_bgr[row, col].astype(np.float32) / 255.0).clip(0.0, 1.0)
|
||||
confidence = max(0.0, min(1.0, (score - cfg.min_ncc) / max(1e-6, 1.0 - cfg.min_ncc)))
|
||||
confidence = max(0.20, min(1.0, 0.35 + confidence * 0.55 + min(0.25, texture)))
|
||||
points.append(
|
||||
RenderPointPacket(
|
||||
stable_key=f"{prefix}:{row}:{col}:{best_col}",
|
||||
xyz=xyz.astype(np.float64),
|
||||
radius_m=cfg.radius_m,
|
||||
color_rgba=(float(r), float(g), float(b), 0.38 + 0.48 * confidence),
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=timestamp_ns,
|
||||
)
|
||||
)
|
||||
return tuple(points)
|
||||
|
||||
|
||||
def _best_horizontal_match(
|
||||
left_patch: np.ndarray,
|
||||
right: np.ndarray,
|
||||
row: int,
|
||||
col: int,
|
||||
radius: int,
|
||||
*,
|
||||
max_disparity_px: int,
|
||||
) -> tuple[int | None, float]:
|
||||
best_col: int | None = None
|
||||
best_score = -1.0
|
||||
min_col = max(radius, col - max_disparity_px)
|
||||
max_col = min(right.shape[1] - radius - 1, col + max_disparity_px // 8)
|
||||
for candidate_col in range(min_col, max_col + 1):
|
||||
score = _ncc(left_patch, _patch(right, row, candidate_col, radius))
|
||||
if score > best_score:
|
||||
best_col = candidate_col
|
||||
best_score = score
|
||||
return best_col, best_score
|
||||
|
||||
|
||||
def _luma(frame_bgr: np.ndarray) -> np.ndarray:
|
||||
if frame_bgr.ndim != 3 or frame_bgr.shape[2] != 3:
|
||||
raise ValueError("frame_bgr must have shape HxWx3")
|
||||
frame = frame_bgr.astype(np.float32) / 255.0
|
||||
return 0.0722 * frame[:, :, 0] + 0.7152 * frame[:, :, 1] + 0.2126 * frame[:, :, 2]
|
||||
|
||||
|
||||
def _patch(image: np.ndarray, row: int, col: int, radius: int) -> np.ndarray:
|
||||
return image[row - radius : row + radius + 1, col - radius : col + radius + 1]
|
||||
|
||||
|
||||
def _ncc(a: np.ndarray, b: np.ndarray) -> float:
|
||||
aa = a.astype(np.float32) - float(np.mean(a))
|
||||
bb = b.astype(np.float32) - float(np.mean(b))
|
||||
denom = float(np.linalg.norm(aa) * np.linalg.norm(bb))
|
||||
if denom < 1e-9:
|
||||
return -1.0
|
||||
return float(np.sum(aa * bb) / denom)
|
||||
Loading…
Reference in a new issue