Files
starcells 45249b59f9 光谱工具集:采集、回放、寻峰、波长标定
- spectro_core.py: 共享核心(加载/标定/基线/寻峰/高斯拟合/双峰联合拟合/CSV-JSON)

- peak_finder.py: 寻峰与峰信息导出,--pick 交互选峰(含 RAW 预览)

- wavelength_calibration.py: 改用 core 寻峰,汞灯 577/579 双峰可分

- wavelength_player.py / hq_average.py: 复用 core 的标定与解码加载
2026-11-14 13:48:24 +08:00

2410 lines
96 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
hq_spectrum.py
==============
Raspberry Pi HQ Camera (IMX477) 12-bit RAW, live R/G/B spectral monitor.
The program follows the stream selected by rpicam-hello for the HQ camera:
sensor mode : 2028x1520 (12 bit, packed)
raw stream : BGGR_PISP_COMP1 / SBGGR12_1X12
sensor Bayer order : BGGR
CFE format : PC1B
It captures the raw stream, *not* the ISP preview. The four Bayer sites are
split into B, Gb/Gr and R planes, a rectangular ROI is reduced along the slit
direction, and the three one-dimensional spectra are drawn with Matplotlib.
The Pi 5 path delivers PiSP-compressed PC1B data (format BGGR_PISP_COMP1).
That buffer is expanded with the same decompressor that Picamera2 uses for
DNG output. On a Pi 4 (or when an uncompressed raw stream is selected), the
SBGGR12 16-bit-container path is used directly. Both paths are supported.
Typical use on the Pi
---------------------
# dependencies (Raspberry Pi OS, use the system Python)
sudo apt install python3-picamera2 python3-numpy python3-matplotlib python3-tk
# list the raw modes your camera exposes
python3 hq_spectrum.py --list-modes
# live display, auto ROI, manual exposure taken from rpicam-hello
python3 hq_spectrum.py --exposure 33013 --gain 16
# fixed ROI in full-resolution sensor pixels: x0,y0,x1,y1
python3 hq_spectrum.py --roi 300,420,1750,980 --exposure 33013 --gain 16
# ROI as fractions of the frame
python3 hq_spectrum.py --roi 0.12,0.30,0.85,0.65
# two-point wavelength calibration made from known lamp lines
python3 hq_spectrum.py --calibrate 420:405,920:546 --exposure 33013 --gain 16
# replay/analyze a recording made by hq_record.py
python3 hq_spectrum.py --input recordings/hg_lamp --fps 15
Keys in the live window
-----------------------
s : save the current figure as PNG and the profiles as CSV
q : quit
Draw a new box with the mouse to change the orange/yellow ROI.
Demo (works on a normal PC, no camera required)
-----------------------------------------------
python3 hq_spectrum.py --demo --frames 1 --headless --save-prefix demo
Notes
-----
* The x axis is sensor column pixels until a wavelength calibration is given.
The R/G/B curves are broad CFA responses, not narrow-band spectrometer
channels; use them to see line positions and relative changes.
* No demosaicing or colour processing is applied. That is intentional: it
keeps the spectral lines from being interpolated across neighbouring pixels.
* Auto exposure is convenient for finding a signal but makes intensity ratios
unstable. For measurements use fixed ExposureTime and AnalogueGain.
* The preview is auto-stretched for visibility; the curves show black-level
corrected raw ADU values.
"""
from __future__ import annotations
import argparse
import csv
import json
import re
import sys
import time
import traceback
from collections import deque
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Optional
import numpy as np
CHANNELS = ("R", "G", "B")
CHANNEL_COLORS = {"R": "#e43d45", "G": "#21a45a", "B": "#2f6fdd"}
BAYER_LAYOUT = {
"RGGB": (("R", 0, 0), ("G", 0, 1), ("G", 1, 0), ("B", 1, 1)),
"BGGR": (("B", 0, 0), ("G", 0, 1), ("G", 1, 0), ("R", 1, 1)),
"GRBG": (("G", 0, 0), ("R", 0, 1), ("B", 1, 0), ("G", 1, 1)),
"GBRG": (("G", 0, 0), ("B", 0, 1), ("R", 1, 0), ("G", 1, 1)),
}
# ---------------------------------------------------------------------------
# Small data containers
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class ROI:
"""A half-open ROI in full-resolution sensor coordinates: [x0,x1) x [y0,y1)."""
x0: int
y0: int
x1: int
y1: int
@property
def width(self) -> int:
return self.x1 - self.x0
@property
def height(self) -> int:
return self.y1 - self.y0
def text(self) -> str:
return f"({self.x0},{self.y0})-({self.x1},{self.y1})"
@dataclass
class SpectrumResult:
roi: ROI
x_px: dict[str, np.ndarray]
x_plot: dict[str, np.ndarray]
signal: dict[str, np.ndarray]
signal_raw: dict[str, np.ndarray]
normalized: dict[str, np.ndarray]
peaks: dict[str, np.ndarray]
preview: np.ndarray
full_size: tuple[int, int]
raw_format: str
bit_depth: int
black: float
full_scale: float
saturated_fraction: float
metadata: dict
x_unit: str
calibration_text: str
timestamp: float
@dataclass
class PlayerState:
"""Transport state for the replay player."""
total_frames: int
fps: float
current: int = 0
playing: bool = False
loop: bool = True
speed: float = 1.0
pending_seek: Optional[int] = None
needs_reschedule: bool = False
def period(self) -> float:
return 1.0 / max(self.fps * self.speed, 0.01)
def request(self, frame: int, pause: bool = True) -> None:
self.pending_seek = max(0, min(self.total_frames - 1, int(frame)))
if pause:
self.playing = False
class Calibration:
"""Polynomial pixel -> wavelength calibration."""
def __init__(self, pairs: list[tuple[float, float]], order: int = 1):
if len(pairs) < 2:
raise ValueError("calibration needs at least two pixel:wavelength pairs")
arr = np.asarray(sorted(pairs), dtype=float)
if np.any(np.diff(arr[:, 0]) <= 0):
raise ValueError("calibration pixel positions must be distinct")
self.pixels = arr[:, 0]
self.wavelengths = arr[:, 1]
degree = max(1, min(int(order), len(pairs) - 1))
self.coeff = np.polyfit(self.pixels, self.wavelengths, degree)
pred = np.polyval(self.coeff, self.pixels)
self.rms_nm = float(np.sqrt(np.mean((pred - self.wavelengths) ** 2)))
def __call__(self, x: np.ndarray) -> np.ndarray:
return np.polyval(self.coeff, np.asarray(x, dtype=float))
def describe(self) -> str:
terms = []
degree = len(self.coeff) - 1
for i, c in enumerate(self.coeff):
power = degree - i
terms.append(f"{c:.6g}*x^{power}" if power else f"{c:.6g}")
return "lambda(nm) = " + " + ".join(terms) + f"; rms={self.rms_nm:.2f} nm"
# ---------------------------------------------------------------------------
# Bayer / raw helpers
# ---------------------------------------------------------------------------
def parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Live R/G/B spectral analysis of Raspberry Pi HQ Camera RAW frames.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--width", type=int, default=2028, help="raw stream width")
parser.add_argument("--height", type=int, default=1520, help="raw stream height")
parser.add_argument(
"--fps", type=float, default=5.0,
help="capture/display rate for live mode; the GUI player uses the recording's fps",
)
parser.add_argument(
"--roi",
default="auto",
help="'auto' or x0,y0,x1,y1 in sensor pixels; values <= 1 are treated as fractions",
)
parser.add_argument(
"--calibrate",
default=None,
metavar="PX:NM[,PX:NM...]",
help="pixel:wavelength pairs, e.g. 420:405,920:546",
)
parser.add_argument("--poly-order", type=int, default=1, help="polynomial order for calibration")
parser.add_argument(
"--smooth", type=int, default=3,
help="moving-average width in sensor pixels (channel samples are 2 px apart)",
)
parser.add_argument(
"--reduce",
choices=("mean", "median"),
default="mean",
help="row reduction inside the ROI",
)
parser.add_argument("--black", type=float, default=None, help="black level override in ADU")
parser.add_argument("--full-scale", type=float, default=None, help="white level override in ADU")
parser.add_argument("--exposure", type=float, default=None, help="manual exposure time in microseconds")
parser.add_argument("--gain", type=float, default=None, help="manual analogue gain")
parser.add_argument(
"--raw-format",
default=None,
help="optional Picamera2 raw format, e.g. SBGGR12 or BGGR_PISP_COMP1",
)
parser.add_argument("--peak-prominence", type=float, default=0.08, help="normalized peak prominence")
parser.add_argument("--peak-height", type=float, default=0.035, help="minimum normalized peak height")
parser.add_argument("--peak-distance", type=float, default=12.0, help="minimum peak spacing in sensor pixels")
parser.add_argument("--max-peaks", type=int, default=5, help="maximum peaks detected per channel")
parser.add_argument("--waterfall-rows", type=int, default=240, help="number of frames in the waterfall")
parser.add_argument("--demo", action="store_true", help="use a synthetic 12-bit BGGR frame")
parser.add_argument(
"--input",
default=None,
metavar="REC_DIR",
help="replay/analyze a recording made by hq_record.py",
)
parser.add_argument(
"--no-loop",
action="store_true",
help="with --input: stop at the end instead of looping playback",
)
parser.add_argument(
"--autoplay",
action="store_true",
help="with --input: start playing immediately instead of paused",
)
parser.add_argument("--headless", action="store_true", help="do not open a window (Agg backend)")
parser.add_argument(
"--no-blit",
action="store_true",
help="redraw the whole figure per frame instead of blitting the changed artists",
)
parser.add_argument(
"--frames", type=int, default=0,
help="stop after N frames for live/headless mode; ignored by the GUI player",
)
parser.add_argument("--save-prefix", default=None, help="save final dashboard/CSV using this path prefix")
parser.add_argument("--no-selector", action="store_true", help="disable mouse ROI selection")
parser.add_argument("--list-modes", action="store_true", help="list camera raw modes and exit")
parser.add_argument("--verbose", action="store_true", help="print extra raw/ROI diagnostics")
args = parser.parse_args(argv)
if args.width < 64 or args.height < 64:
parser.error("width and height must be at least 64")
if args.fps <= 0:
parser.error("--fps must be positive")
if args.max_peaks < 0:
parser.error("--max-peaks must be >= 0")
if args.waterfall_rows < 2:
parser.error("--waterfall-rows must be >= 2")
if args.frames < 0:
parser.error("--frames must be >= 0")
if args.demo and args.input:
parser.error("--demo and --input are mutually exclusive")
return args
def pattern_from_format(fmt: str) -> str:
match = re.search(r"([RGB]{4})", str(fmt).upper())
if not match or match.group(1) not in BAYER_LAYOUT:
raise ValueError(f"cannot determine Bayer order from raw format {fmt!r}")
return match.group(1)
def bit_depth_from_format(fmt: str) -> int:
if "PISP_COMP" in str(fmt).upper():
return 16
match = re.search(r"([RGB]{4})(\d+)", str(fmt).upper())
return int(match.group(2)) if match else 16
def make_roi(x0: float, y0: float, x1: float, y1: float, width: int, height: int) -> ROI:
"""Clamp and align a ROI to even sensor coordinates (needed by the Bayer grid)."""
def edge(value: float, upper: int) -> int:
return int(round(max(0.0, min(float(upper), float(value)))))
xa, xb = sorted((edge(x0, width), edge(x1, width)))
ya, yb = sorted((edge(y0, height), edge(y1, height)))
width_max = width - (width % 2)
height_max = height - (height % 2)
xa = min(xa, width_max - 2)
ya = min(ya, height_max - 2)
xa -= xa % 2
ya -= ya % 2
xb = min(xb, width_max)
yb = min(yb, height_max)
xb = max(xa + 2, xb - ((xb - xa) % 2))
yb = max(ya + 2, yb - ((yb - ya) % 2))
return ROI(int(xa), int(ya), int(xb), int(yb))
def parse_roi(value: str, width: int, height: int) -> Optional[ROI]:
value = value.strip().lower()
if value == "auto":
return None
parts = [p.strip() for p in value.split(",")]
if len(parts) != 4:
raise ValueError("--roi must be 'auto' or x0,y0,x1,y1")
try:
numbers = [float(p) for p in parts]
except ValueError as exc:
raise ValueError("ROI values must be numbers") from exc
if not all(np.isfinite(v) for v in numbers):
raise ValueError("ROI values must be finite")
if all(0.0 <= v <= 1.0 for v in numbers):
numbers = [numbers[0] * width, numbers[1] * height, numbers[2] * width, numbers[3] * height]
roi = make_roi(*numbers, width, height)
if roi.width < 24 or roi.height < 8:
raise ValueError("ROI is too small")
return roi
def decompress_pisp_comp1(array: np.ndarray) -> np.ndarray:
"""Expand a PiSP PC1B/COMP1 raw buffer to a 2-D uint16 Bayer image.
Adapted from Picamera2's helpers.decompress() (BSD-2-Clause,
Raspberry Pi Ltd.); see THIRD_PARTY_NOTICES.md. Keeping a local copy
makes the analyser work with older Picamera2 versions and avoids
depending on a helper method.
"""
array = np.ascontiguousarray(array)
if array.dtype != np.uint8:
array = array.view(np.uint8)
if array.ndim != 2:
raise ValueError(f"unexpected PC1B buffer shape {array.shape}")
# PC1B works in 8-byte groups. Some libcamera versions report the
# compressed stride as the natural width (e.g. 2028) rather than a padded
# value, so zero-pad the tail of each row before expanding it.
if array.shape[1] % 8:
pad = (-array.shape[1]) % 8
array = np.pad(array, ((0, 0), (0, pad)), mode="constant")
offset = 2048
words = array.view(np.int32)
words = words.reshape((words.shape[0], words.shape[1] // 2, 2))
qmode = words & 3
pix0 = (words >> 2) & 511
pix1 = ((words >> 11) & 127) - 64
pix2 = (words >> 18) & 127
pix3 = (words >> 25) & 127
# qmode 0..2: four deltas around a 9-bit base value.
low = qmode * pix0 < 768
q1 = np.copy(pix0)
q2 = pix1 + 448
np.maximum(pix0, pix0 - pix1, where=low, out=q1)
np.maximum(pix0, pix0 + pix1, where=low, out=q2)
gain = np.right_shift(1536, qmode)
q0 = np.minimum(gain, np.maximum(q1 - 64, 0)) + pix2
q3 = np.minimum(gain, np.maximum(q2 - 64, 0)) + pix3
np.maximum(np.maximum(16 * q0, 32 * (q0 - 160)), 64 * qmode * q0, out=pix0)
np.maximum(np.maximum(16 * q1, 32 * (q1 - 160)), 64 * qmode * q1, out=pix1)
np.maximum(np.maximum(16 * q2, 32 * (q2 - 160)), 64 * qmode * q2, out=pix2)
np.maximum(np.maximum(16 * q3, 32 * (q3 - 160)), 64 * qmode * q3, out=pix3)
# qmode 3 is a second, independent 16-bit coding of the same word that
# overrides the values above. On ordinary sensor data roughly one word in
# ten thousand uses it, so decode just those words: the full-frame version
# of this block costs ~30 % of the whole frame.
q3mode = qmode == 3
if q3mode.any():
index = np.flatnonzero(q3mode)
word = words.reshape(-1)[index]
high = (word >> 2) & 32767
low = (word >> 17) & 32767
codes = ((high & 15) + 16 * ((high >> 8) // 11),
(high >> 4) % 176,
(low & 15) + 16 * ((low >> 8) // 11),
(low >> 4) % 176)
for plane, code in zip((pix0, pix1, pix2, pix3), codes):
plane.reshape(-1)[index] = np.maximum(256 * code, 512 * (code - 47))
# Every 8-byte group holds four sites x two words, and the flattened
# memory order is group -> site -> word, so write the pixels straight into
# the uint16 result instead of stacking four full-frame int32 planes and
# converting the 12 MB copy afterwards.
res = np.empty(array.shape, dtype=np.uint16)
groups = res.reshape(res.shape[0], -1, 8)
for index, plane in enumerate((pix0, pix1, pix2, pix3)):
np.add(plane, offset, out=plane)
np.minimum(plane, 65535, out=plane)
groups[:, :, 2 * index] = plane[:, :, 0]
groups[:, :, 2 * index + 1] = plane[:, :, 1]
return res
def unpack_csi2(data: np.ndarray, bit_depth: int) -> np.ndarray:
"""Unpack MIPI CSI-2 packed 10/12-bit rows (stride-sized raw rows)."""
height, stride = data.shape
if bit_depth == 12:
if stride % 3:
raise ValueError(f"12-bit packed stride {stride} is not a multiple of 3")
width = stride // 3 * 2
groups = np.ascontiguousarray(data).reshape(height, stride // 3, 3).astype(np.uint16)
out = np.empty((height, width), dtype=np.uint16)
out[:, 0::2] = groups[:, :, 0] | ((groups[:, :, 1] & 0x0F) << 8)
out[:, 1::2] = (groups[:, :, 1] >> 4) | (groups[:, :, 2] << 4)
return out
if bit_depth == 10:
if stride % 5:
raise ValueError(f"10-bit packed stride {stride} is not a multiple of 5")
width = stride // 5 * 4
groups = np.ascontiguousarray(data).reshape(height, stride // 5, 5).astype(np.uint16)
out = np.empty((height, width), dtype=np.uint16)
out[:, 0::4] = groups[:, :, 0] | ((groups[:, :, 1] & 0x03) << 8)
out[:, 1::4] = (groups[:, :, 1] >> 2) | ((groups[:, :, 2] & 0x0F) << 6)
out[:, 2::4] = (groups[:, :, 2] >> 4) | ((groups[:, :, 3] & 0x3F) << 4)
out[:, 3::4] = (groups[:, :, 3] >> 6) | (groups[:, :, 4] << 2)
return out
raise ValueError(f"unsupported packed bit depth {bit_depth}")
def decode_raw(raw: np.ndarray, config: dict, fmt: str) -> tuple[np.ndarray, int]:
"""Turn a Picamera2 raw buffer into a 2-D uint16 Bayer image.
Picamera2's raw stream is normally a uint8 byte buffer of shape
(height, stride), including for 16-bit container formats. A few code
paths / future versions can hand over an already-unpacked uint16 array;
both representations are accepted here.
"""
raw = np.asarray(raw)
width, height = (int(v) for v in config["size"])
stride = int(config.get("stride") or (width * 2))
fmt = str(fmt)
upper = fmt.upper()
if raw.ndim == 1:
if raw.dtype == np.uint8:
raw = raw.reshape(height, stride)
elif raw.dtype.itemsize == 2:
raw = raw.reshape(height, -1)
else:
raise ValueError(f"unsupported raw dtype {raw.dtype}")
if raw.ndim != 2 or raw.shape[0] != height:
raise ValueError(f"raw buffer shape {raw.shape} does not match {height}x{width}")
if "PISP_COMP1" in upper:
if raw.dtype != np.uint8:
raise ValueError("PC1B raw buffer must be a uint8 byte buffer")
image = decompress_pisp_comp1(raw)
if image.shape[1] < width:
raise ValueError(f"decompressed raw has only {image.shape[1]} columns, expected {width}")
return np.ascontiguousarray(image[:, :width]), 16
bit_depth = bit_depth_from_format(fmt)
mask = (1 << bit_depth) - 1 if bit_depth < 16 else None
if raw.dtype.itemsize == 2:
# Already unpacked samples: shape is (height, stride_in_samples).
if raw.shape[1] < width:
raise ValueError(
f"unpacked raw has only {raw.shape[1]} columns, expected {width}; format={fmt!r}"
)
image = raw[:, :width].astype(np.uint16, copy=True)
if mask is not None:
image &= mask
return image, bit_depth
if "CSI2P" in upper or "_1X12" in upper or "_1X10" in upper:
# Stride is often padded (e.g. to 32 bytes). Unpack only the real row
# payload, otherwise the padding is interpreted as extra pixels.
row_bytes = (width * bit_depth + 7) // 8
if raw.shape[1] < row_bytes:
raise ValueError(f"packed raw stride {raw.shape[1]} is too small for {width} pixels")
image = unpack_csi2(np.ascontiguousarray(raw[:, :row_bytes]), bit_depth)
if image.shape[1] < width:
raise ValueError(f"unpacked raw has only {image.shape[1]} columns, expected {width}")
return np.ascontiguousarray(image[:, :width]), bit_depth
if bit_depth == 8:
if raw.shape[1] < width:
raise ValueError(f"raw stride {raw.shape[1]} is narrower than {width}")
return np.ascontiguousarray(raw[:, :width]).astype(np.uint16), 8
need = width * 2
if raw.shape[1] < need:
raise ValueError(
f"raw stride {raw.shape[1]} is too small for {width} 16-bit samples; "
f"format={fmt!r}"
)
image = np.ascontiguousarray(raw[:, :need]).view("<u2").reshape(height, width)
if mask is not None:
image = image & mask
return image, bit_depth
def resolve_levels(meta, bit_depth, black_override, full_override):
full = (
float(full_override)
if full_override is not None
else float((1 << bit_depth) - 1)
)
if black_override is not None:
black = float(black_override)
else:
# Prefer BlackLevel, then fall back to SensorBlackLevels.
value = meta.get("BlackLevel")
if value is None:
value = meta.get("SensorBlackLevels")
if value is None:
value = 0.0
if isinstance(value, (tuple, list, np.ndarray)):
values = np.asarray(value, dtype=float)
values = values[np.isfinite(values)]
black = float(np.mean(values)) if values.size else 0.0
else:
black = float(value)
if not np.isfinite(black) or black < 0:
black = 0.0
if black >= full:
black = black * full / 65535.0
return black, full
# ---------------------------------------------------------------------------
# Preview, ROI and spectrum processing
# ---------------------------------------------------------------------------
def extract_planes(raw: np.ndarray, pattern: str, roi: ROI) -> dict[str, np.ndarray]:
"""Extract R, G and B planes from a BGGR/RGGB/... ROI.
The two green sites are averaged. All returned planes have the same shape
because the ROI is aligned to even coordinates.
"""
if roi.width < 2 or roi.height < 2:
raise ValueError(f"ROI is empty or too small: {roi.text()}")
crop = raw[roi.y0:roi.y1, roi.x0:roi.x1]
if crop.size == 0 or crop.shape[0] < 2 or crop.shape[1] < 2:
raise ValueError(f"ROI {roi.text()} does not overlap the raw frame")
layout = BAYER_LAYOUT[pattern]
by_color: dict[str, list[np.ndarray]] = {c: [] for c in CHANNELS}
for color, dy, dx in layout:
by_color[color].append(crop[dy::2, dx::2])
planes: dict[str, np.ndarray] = {}
for color, arrays in by_color.items():
if color == "G" and len(arrays) == 2:
rows = min(a.shape[0] for a in arrays)
cols = min(a.shape[1] for a in arrays)
planes[color] = (arrays[0][:rows, :cols].astype(np.float32) +
arrays[1][:rows, :cols].astype(np.float32)) * 0.5
else:
planes[color] = arrays[0].astype(np.float32)
return planes
def channel_x_positions(roi: ROI, pattern: str, count_g: int, count_rb: int) -> dict[str, np.ndarray]:
"""Full-resolution sensor x coordinate for every CFA sample."""
positions = {}
for color, dy, dx in BAYER_LAYOUT[pattern]:
if color == "G":
positions[color] = roi.x0 + 0.5 + 2.0 * np.arange(count_g, dtype=float)
else:
positions[color] = roi.x0 + float(dx) + 2.0 * np.arange(count_rb, dtype=float)
return positions
def smooth_vector(y: np.ndarray, width: int) -> np.ndarray:
width = int(width)
if width <= 1 or y.size == 0:
return y.astype(np.float32, copy=True)
width = min(width, y.size)
if width <= 1:
return y.astype(np.float32, copy=True)
# Symmetric edge padding works for both odd and even window widths.
left = (width - 1) // 2
right = width // 2
padded = np.pad(y.astype(np.float32), (left, right), mode="edge")
kernel = np.ones(width, dtype=np.float32) / width
return np.convolve(padded, kernel, mode="valid").astype(np.float32)
def find_peaks_normalized(y: np.ndarray, x: np.ndarray, min_distance: int,
prominence: float, min_height: float,
max_peaks: int) -> np.ndarray:
"""A small scipy-free local-maximum/prominence finder."""
n = y.size
if n < 3 or max_peaks <= 0:
return np.empty(0, dtype=int)
candidates = np.where((y[1:-1] >= y[:-2]) & (y[1:-1] > y[2:]))[0] + 1
if candidates.size == 0:
return np.empty(0, dtype=int)
# Highest first, then suppress neighbours.
candidates = candidates[np.argsort(y[candidates])[::-1]]
min_distance = max(1, int(min_distance))
prom_window = max(8, min_distance * 4)
kept: list[int] = []
for idx in candidates:
if y[idx] < min_height:
continue
if any(abs(int(idx) - k) < min_distance for k in kept):
continue
left = y[max(0, idx - prom_window):idx]
right = y[idx + 1:min(n, idx + 1 + prom_window)]
if left.size == 0 or right.size == 0:
base = 0.0
else:
base = max(float(left.min()), float(right.min()))
if float(y[idx]) - base < prominence:
continue
kept.append(int(idx))
if len(kept) >= max_peaks:
break
kept.sort(key=lambda i: float(x[i]))
return np.asarray(kept, dtype=int)
def _block_sum(plane: np.ndarray, factor: int) -> np.ndarray:
"""Sum ``factor`` x ``factor`` blocks of a 2-D integer plane."""
height, width = plane.shape
height -= height % factor
width -= width % factor
if height <= 0 or width <= 0:
return plane
return plane[:height, :width].reshape(
height // factor, factor, width // factor, factor
).sum(axis=(1, 3), dtype=np.uint32)
def make_preview(raw: np.ndarray, pattern: str, target_width: int = 640) -> np.ndarray:
"""Quick, ISP-free RGB preview by binning the four Bayer sites.
The whole frame is viewed as 2x2 Bayer cells, so every site is a plain
slice of that view and the arithmetic stays integer until the final
stretch. The 1st/99.6th percentiles are estimated from a coarse
subsample: a preview does not need a per-frame exact percentile and the
exact version is what made this function the most expensive part of a
frame.
"""
height = raw.shape[0] - (raw.shape[0] % 2)
width = raw.shape[1] - (raw.shape[1] % 2)
if height < 2 or width < 2:
raise ValueError(f"frame {raw.shape} is too small for a preview")
sub = raw[:height, :width]
if not sub.flags.c_contiguous:
sub = np.ascontiguousarray(sub)
cells = sub.reshape(height // 2, 2, width // 2, 2)
layout = BAYER_LAYOUT[pattern]
sites: dict[str, list[np.ndarray]] = {c: [] for c in CHANNELS}
for color, dy, dx in layout:
sites[color].append(cells[:, dy, :, dx])
factor = max(1, int(np.ceil((width // 2) / float(target_width))))
channels = []
for color in CHANNELS:
arrays = sites[color]
plane = arrays[0].astype(np.uint32)
for extra in arrays[1:]:
plane += extra
if len(arrays) > 1:
plane //= len(arrays)
if factor > 1:
plane = _block_sum(plane, factor)
channels.append(plane)
sums = np.stack(channels, axis=-1)
# ~40k samples per channel are plenty for a 1 % / 99.6 % stretch and keep
# the percentile search at ~1 ms instead of ~15 ms for the full frame.
step = max(1, int(round(max(sums.shape[0], sums.shape[1]) / 256.0)))
sample = sums[::step, ::step].reshape(-1, 3)
lo, hi = np.percentile(sample, (1.0, 99.6), axis=0)
lo = lo.astype(np.float32)
scale = np.maximum((hi - lo).astype(np.float32), 1.0)
out = sums.astype(np.float32)
out -= lo
out /= scale
np.clip(out, 0.0, 1.0, out=out)
return np.power(out, 0.8, dtype=np.float32)
def detect_auto_roi(preview: np.ndarray, full_width: int, full_height: int) -> Optional[ROI]:
"""Find a horizontal spectral band from a stretched preview."""
height, width = preview.shape[:2]
if height < 8 or width < 8:
return None
luminance = 0.299 * preview[..., 0] + 0.587 * preview[..., 1] + 0.114 * preview[..., 2]
block = max(2, min(12, min(height, width) // 24))
hh = (height // block) * block
ww = (width // block) * block
if hh < block or ww < block:
return None
blocks = luminance[:hh, :ww].reshape(hh // block, block, ww // block, block).mean(axis=(1, 3))
background = float(np.median(blocks))
mad = float(np.median(np.abs(blocks - background)))
high = float(np.percentile(blocks, 99.9))
threshold = background + max(8.0 * 1.4826 * mad, 0.02 * (high - background))
mask = blocks > threshold
if int(mask.sum()) < 4:
return None
row_counts = mask.sum(axis=1)
active_rows = np.where(row_counts >= max(1.0, 0.12 * row_counts.max()))[0]
if active_rows.size == 0:
return None
r0, r1 = int(active_rows.min()), int(active_rows.max()) + 1
band = mask[r0:r1, :]
col_counts = band.sum(axis=0)
active_cols = np.where(col_counts > 0)[0]
if active_cols.size == 0:
return None
c0, c1 = int(active_cols.min()), int(active_cols.max()) + 1
scale_x = full_width / float(width)
scale_y = full_height / float(height)
x0 = c0 * block * scale_x
x1 = c1 * block * scale_x
y0 = r0 * block * scale_y
y1 = r1 * block * scale_y
# Keep some dark baseline and make sure a narrow band still has context.
margin_x = 0.035 * full_width
margin_y = 0.035 * full_height
x0, x1 = x0 - margin_x, x1 + margin_x
y0, y1 = y0 - margin_y, y1 + margin_y
if x1 - x0 < 0.18 * full_width:
center = 0.5 * (x0 + x1)
x0, x1 = center - 0.09 * full_width, center + 0.09 * full_width
if y1 - y0 < 0.08 * full_height:
center = 0.5 * (y0 + y1)
y0, y1 = center - 0.04 * full_height, center + 0.04 * full_height
roi = make_roi(x0, y0, x1, y1, full_width, full_height)
if roi.width < 32 or roi.height < 8:
return None
return roi
def process_frame(raw: np.ndarray, meta: dict, roi: ROI, pattern: str,
args: argparse.Namespace, calibration: Optional[Calibration],
full_size: tuple[int, int], raw_format: str,
bit_depth: int) -> SpectrumResult:
planes = extract_planes(raw, pattern, roi)
if args.reduce == "median":
profiles = {c: np.median(planes[c], axis=0).astype(np.float32) for c in CHANNELS}
else:
profiles = {c: np.mean(planes[c], axis=0, dtype=np.float32) for c in CHANNELS}
counts_g = min(planes["R"].shape[1], planes["B"].shape[1], planes["G"].shape[1])
counts_rb = min(planes["R"].shape[1], planes["B"].shape[1])
positions = channel_x_positions(roi, pattern, counts_g, counts_rb)
black, full_scale = resolve_levels(meta, bit_depth, args.black, args.full_scale)
signal = {}
signal_raw = {}
normalized = {}
peaks = {}
x_px = {}
x_plot = {}
unit = "nm" if calibration is not None else "px"
peak_distance_samples = max(1, int(round(args.peak_distance / 2.0)))
smooth_samples = 1 if args.smooth <= 1 else max(1, (args.smooth + 1) // 2)
for channel in CHANNELS:
n = min(profiles[channel].size, positions[channel].size)
y = np.maximum(profiles[channel][:n] - black, 0.0).astype(np.float32)
ys = smooth_vector(y, smooth_samples)
sig = np.clip(ys, 0.0, None)
base = float(np.percentile(sig, 5.0)) if sig.size else 0.0
norm = np.clip(sig - base, 0.0, None)
peak = float(norm.max()) if norm.size else 0.0
if peak > 0:
norm /= peak
else:
norm[:] = 0.0
x = positions[channel][:n]
x_display = calibration(x) if calibration is not None else x.copy()
idx = find_peaks_normalized(
norm, x_display, peak_distance_samples,
args.peak_prominence, args.peak_height, args.max_peaks
)
x_px[channel] = x
x_plot[channel] = x_display
signal[channel] = sig
signal_raw[channel] = y
normalized[channel] = norm
peaks[channel] = idx
preview = make_preview(raw, pattern)
roi_raw = raw[roi.y0:roi.y1, roi.x0:roi.x1]
saturated = float(np.mean(roi_raw >= (0.995 * full_scale))) if roi_raw.size else 0.0
return SpectrumResult(
roi=roi,
x_px=x_px,
x_plot=x_plot,
signal=signal,
signal_raw=signal_raw,
normalized=normalized,
peaks=peaks,
preview=preview,
full_size=full_size,
raw_format=raw_format,
bit_depth=bit_depth,
black=black,
full_scale=full_scale,
saturated_fraction=saturated,
metadata=meta,
x_unit=unit,
calibration_text=calibration.describe() if calibration is not None else "uncalibrated (sensor x)",
timestamp=time.time(),
)
# ---------------------------------------------------------------------------
# Synthetic source (also useful for testing on a laptop)
# ---------------------------------------------------------------------------
class DemoSource:
"""A BGGR 12-bit synthetic spectral frame with a horizontal dispersion axis."""
description = "synthetic HQ-camera-like BGGR12 frame"
def __init__(self, args: argparse.Namespace):
self.args = args
self.full_size = (args.width - args.width % 2, args.height - args.height % 2)
self.raw_format = "SBGGR12 (demo)"
self.bit_depth = 12
self.pattern = "BGGR"
self.stride = self.full_size[0] * 2
self.rng = np.random.default_rng(20261023)
self.frame_index = 0
self.base = self._build_base()
self.meta = {
"ExposureTime": 33013,
"AnalogueGain": 16.0,
"DigitalGain": 1.0,
"BlackLevel": 256,
"Lux": 12.0,
"SensorTimestamp": time.monotonic_ns(),
"Demo": True,
}
def _gaussian(self, x: np.ndarray, center: float, sigma: float) -> np.ndarray:
return np.exp(-0.5 * ((x - center) / sigma) ** 2)
def _build_base(self) -> np.ndarray:
width, height = self.full_size
w2, h2 = width // 2, height // 2
x = 2.0 * np.arange(w2) + 0.5
x0, x1 = 0.12 * width, 0.88 * width
wavelength = np.interp(x, (x0, x1), (380.0, 760.0), left=np.nan, right=np.nan)
valid = np.isfinite(wavelength)
wl = np.where(valid, wavelength, 550.0)
# Mercury/neon-like line mixture on a small continuum.
radiance = np.where(valid, 0.10 + 0.00002 * (wl - 380.0), 0.0)
for center, amplitude, sigma in (
(404.7, 0.40, 1.7),
(435.8, 1.00, 2.1),
(546.1, 0.92, 2.4),
(577.0, 0.45, 2.0),
(579.1, 0.40, 2.0),
(611.6, 0.34, 2.3),
(696.5, 0.48, 3.0),
):
radiance = radiance + amplitude * self._gaussian(wl, center, sigma) * valid
# Broad CFA response curves (illustrative, not a measured QE curve).
response = {
"R": 0.95 * self._gaussian(wl, 615.0, 78.0) + 0.10 * self._gaussian(wl, 540.0, 55.0),
"G": 0.88 * self._gaussian(wl, 545.0, 68.0) + 0.12 * self._gaussian(wl, 455.0, 45.0) + 0.08 * self._gaussian(wl, 635.0, 55.0),
"B": 0.90 * self._gaussian(wl, 458.0, 55.0) + 0.08 * self._gaussian(wl, 535.0, 60.0),
}
# Horizontal slit image: a soft vertical band with a little tilt and texture.
yy = np.arange(h2, dtype=np.float32)
tilt = 2.0 * np.sin(np.linspace(0.0, 1.0, w2) * np.pi)
center_y = 0.53 * h2 + tilt
vertical = np.exp(-0.5 * ((yy[:, None] - center_y[None, :]) / (0.075 * h2)) ** 2)
vignette = 1.0 - 0.18 * ((x - 0.5 * width) / (0.5 * width)) ** 2
channel_images = {}
for channel in CHANNELS:
signal = radiance[None, :] * response[channel][None, :] * vertical
signal *= 2600.0 * vignette[None, :]
signal += 256.0 + 18.0 * np.linspace(0.0, 1.0, w2)[None, :]
channel_images[channel] = signal.astype(np.float32)
raw = np.empty((h2 * 2, w2 * 2), dtype=np.float32)
raw[0::2, 0::2] = channel_images["B"]
raw[0::2, 1::2] = channel_images["G"]
raw[1::2, 0::2] = channel_images["G"]
raw[1::2, 1::2] = channel_images["R"]
# A few hot pixels make sure the row reduction is not blindly trusting
# a single pixel. Mean reduction still works because they are rare.
for _ in range(80):
raw[self.rng.integers(0, raw.shape[0]), self.rng.integers(0, raw.shape[1])] = 4095.0
return raw
def start(self) -> None:
pass
def read(self) -> tuple[np.ndarray, dict]:
self.frame_index += 1
flicker = 1.0 + 0.012 * np.sin(self.frame_index * 0.23)
noise = self.rng.normal(0.0, 3.0, self.base.shape).astype(np.float32)
raw = np.clip(self.base * flicker + noise, 0.0, 4095.0).astype(np.uint16)
meta = dict(self.meta)
meta["SensorTimestamp"] = time.monotonic_ns()
meta["Lux"] = float(12.0 + 0.3 * np.sin(self.frame_index * 0.17))
return raw, meta
def close(self) -> None:
pass
class CameraSource:
"""Picamera2 raw source; decodes PC1B or uncompressed SBGGR12."""
def __init__(self, args: argparse.Namespace):
self.args = args
try:
from picamera2 import Picamera2
except Exception as exc: # pragma: no cover - depends on the Pi
raise RuntimeError(
"Picamera2 is not available. On Raspberry Pi OS use the system Python:\n"
" sudo apt install python3-picamera2\n"
" python3 hq_spectrum.py ..."
) from exc
self.picam2 = Picamera2()
model = str(self.picam2.camera_properties.get("Model", "Raspberry Pi camera"))
self.description = "HQ Camera (IMX477)" if "imx477" in model.lower() else model
self._configure()
cfg = self.picam2.camera_config["raw"]
self.full_size = (int(cfg["size"][0]), int(cfg["size"][1]))
self.raw_format = str(cfg["format"])
self.stride = int(cfg["stride"])
self.pattern = pattern_from_format(self.raw_format)
self.bit_depth = bit_depth_from_format(self.raw_format)
self.camera_config_raw = cfg
self._started = False
def _controls(self) -> dict:
controls: dict = {"FrameRate": float(self.args.fps)}
if self.args.exposure is not None or self.args.gain is not None:
controls["AeEnable"] = False
controls["ExposureTime"] = int(self.args.exposure if self.args.exposure is not None else 10000)
controls["AnalogueGain"] = float(self.args.gain if self.args.gain is not None else 1.0)
return controls
def _configure(self) -> None:
requested = self.args.raw_format.upper() if self.args.raw_format else None
def configure_with(use_format: Optional[str]) -> None:
cfg = {"size": (self.args.width, self.args.height)}
if use_format:
cfg["format"] = use_format
config = self.picam2.create_video_configuration(
main={"size": (320, 240)},
raw=cfg,
controls=self._controls(),
buffer_count=4,
)
self.picam2.configure(config)
try:
configure_with(requested)
except Exception as exc:
if not requested:
raise
print(f"warning: raw format {requested!r} was rejected ({exc}); retrying with automatic format",
file=sys.stderr)
configure_with(None)
def start(self) -> None:
self.picam2.start()
self._started = True
def _capture(self, decode: bool):
request = self.picam2.capture_request()
try:
raw_bytes = request.make_array("raw")
meta = request.get_metadata()
image = None
if decode:
# Decode while the request is still alive; make_array()
# normally copies, but a future version might return a view.
image, _ = decode_raw(raw_bytes, self.camera_config_raw, self.raw_format)
finally:
request.release()
if decode:
return image, meta
return raw_bytes, meta
def read_raw(self) -> tuple[np.ndarray, dict]:
"""Return the raw byte buffer (height x stride) without decoding."""
return self._capture(False)
def read(self) -> tuple[np.ndarray, dict]:
return self._capture(True)
def close(self) -> None:
try:
if self._started:
self.picam2.stop()
finally:
self.picam2.close()
class RecordingSource:
"""Replay a recording written by hq_record.py."""
def __init__(self, directory: str):
self.path = Path(directory).expanduser()
meta_path = self.path / "meta.json"
if not meta_path.is_file():
raise RuntimeError(f"recording metadata not found: {meta_path}")
try:
with open(meta_path, "r", encoding="utf-8") as handle:
meta = json.load(handle)
except Exception as exc:
raise RuntimeError(f"cannot read {meta_path}: {exc}") from exc
for key in ("width", "height", "raw_format", "stride"):
if key not in meta:
raise RuntimeError(f"{meta_path} is missing the {key!r} field")
self.meta = dict(meta)
self.base_meta = dict(meta)
if "BlackLevel" not in self.base_meta and "black_level" in meta:
self.base_meta["BlackLevel"] = meta["black_level"]
self.full_size = (int(meta["width"]), int(meta["height"]))
self.stride = int(meta["stride"])
self.raw_format = str(meta["raw_format"])
self.pattern = str(meta.get("pattern") or pattern_from_format(self.raw_format))
self.bit_depth = int(meta.get("bit_depth") or bit_depth_from_format(self.raw_format))
self.frame_bytes = int(meta.get("frame_bytes") or self.stride * self.full_size[1])
if self.stride <= 0 or self.frame_bytes <= 0:
raise RuntimeError(f"{meta_path} has an invalid stride/frame_bytes")
if self.frame_bytes != self.stride * self.full_size[1]:
raise RuntimeError(
f"{meta_path}: frame_bytes={self.frame_bytes} does not match "
f"stride*height={self.stride * self.full_size[1]}"
)
self.frames_path = self.path / "frames.bin"
self.metadata_path = self.path / "frames.jsonl"
if not self.frames_path.is_file():
raise RuntimeError(f"frames file not found: {self.frames_path}")
self.description = f"replay {self.path.name}"
self.needs_warmup = False
self.index = 0
self.total_frames = 0
self._fp = None
self._meta_fp = None
self._meta_offsets: list[int] = []
def start(self) -> None:
file_size = self.frames_path.stat().st_size
file_frames = file_size // self.frame_bytes
meta_frames = int(self.meta.get("frames") or 0)
self.total_frames = min(file_frames, meta_frames) if meta_frames > 0 else file_frames
if self.total_frames <= 0:
raise RuntimeError(f"recording {self.path} contains no complete frames")
self._fp = open(self.frames_path, "rb")
self._meta_offsets = []
if self.metadata_path.is_file():
self._meta_fp = open(self.metadata_path, "r", encoding="utf-8")
# Index JSONL lines so the player can seek to an arbitrary frame.
while True:
pos = self._meta_fp.tell()
line = self._meta_fp.readline()
if not line:
break
self._meta_offsets.append(pos)
self._meta_fp.seek(0)
self.index = 0
print(f"replay : {self.path} {self.total_frames} frames")
def rewind(self) -> None:
self.index = 0
if self._fp is not None:
self._fp.seek(0)
if self._meta_fp is not None:
self._meta_fp.seek(0)
def _metadata_at(self, index: int) -> dict:
if self._meta_fp is None or index >= len(self._meta_offsets):
return {}
self._meta_fp.seek(self._meta_offsets[index])
line = self._meta_fp.readline()
if not line:
return {}
try:
record = json.loads(line)
except json.JSONDecodeError:
return {}
if not isinstance(record, dict):
return {}
nested = record.pop("metadata", None)
if isinstance(nested, dict):
return {**nested, **record}
return record
def read_at(self, index: int) -> tuple[np.ndarray, dict]:
if self._fp is None:
raise RuntimeError("RecordingSource.start() was not called")
if index < 0:
raise IndexError(index)
if index >= self.total_frames:
raise StopIteration
self._fp.seek(index * self.frame_bytes)
data = self._fp.read(self.frame_bytes)
if len(data) != self.frame_bytes:
raise StopIteration
raw = np.frombuffer(data, dtype=np.uint8).reshape(self.full_size[1], self.stride)
meta = dict(self.base_meta)
meta.update(self._metadata_at(index))
meta["_frame_index"] = index + 1
meta["_frame_total"] = self.total_frames
image, _ = decode_raw(
raw,
{"size": self.full_size, "stride": self.stride},
self.raw_format,
)
self.index = index + 1
return image, meta
def read(self) -> tuple[np.ndarray, dict]:
if self._fp is None:
raise RuntimeError("RecordingSource.start() was not called")
if self.index >= self.total_frames:
raise StopIteration
return self.read_at(self.index)
def close(self) -> None:
if self._fp is not None:
self._fp.close()
self._fp = None
if self._meta_fp is not None:
self._meta_fp.close()
self._meta_fp = None
def list_camera_modes() -> None:
try:
from picamera2 import Picamera2
except Exception as exc:
raise RuntimeError("Picamera2 is not available. Try: sudo apt install python3-picamera2") from exc
cam = Picamera2()
try:
model = cam.camera_properties.get("Model", "unknown camera")
print(f"Camera: {model}")
print(f"{'format':26s} {'size':>12s} {'bit':>3s} {'fps':>6s}")
print("-" * 56)
for mode in cam.sensor_modes:
size = mode.get("size", ("?", "?"))
bits = mode.get("bit_depth", "?")
fps = mode.get("fps", "?")
print(f"{str(mode.get('format', '?')):26s} {size[0]:5d}x{size[1]:<5d} {str(bits):>3s} {str(fps):>6s}")
finally:
cam.close()
# ---------------------------------------------------------------------------
# Matplotlib dashboard
# ---------------------------------------------------------------------------
def _nice_ceiling(value: float) -> float:
"""Round up to 1/1.5/2/2.5/3/4/5/6/8 x a power of ten."""
if not np.isfinite(value) or value <= 0.0:
return 1.0
exponent = 10.0 ** np.floor(np.log10(value))
for factor in (1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0):
if value <= factor * exponent:
return float(factor * exponent)
return float(10.0 * exponent)
def _nice_floor(value: float) -> float:
"""Round down to a nice number (mirror image of _nice_ceiling)."""
if not np.isfinite(value) or value >= 0.0:
return 0.0
return -_nice_ceiling(-value)
class Dashboard:
def __init__(self, plt, args: argparse.Namespace, full_size: tuple[int, int],
description: str, calibration_text: str, on_roi=None,
player: Optional[PlayerState] = None):
self.plt = plt
self.args = args
self.full_w, self.full_h = full_size
self.on_roi = on_roi
self.selector = None
self.save_callback = None
self.last_result: Optional[SpectrumResult] = None
self.headless = args.headless
self.quit_requested = False
self.player = player
self._player_syncing = False
self.btn_play = None
self.btn_loop = None
self.btn_speed = None
self.caption = None
self.ax_slider = None
self.player_slider = None
# Blitting: keep a cached background and repaint only the artists whose
# data changed. A full Matplotlib draw of this dashboard costs several
# times more than the capture + analysis of a frame, and almost none of
# that time is spent on the curves or images themselves.
self.fast = (not self.headless) and not getattr(args, "no_blit", False)
self._bg = None
self._bg_state = None
self._bg_size = None
self._force_full = False
self._paint_groups: list[tuple] = []
self._wf_rows = max(2, int(getattr(args, "waterfall_rows", 240)))
self._wf_buf: Optional[np.ndarray] = None
# These default Matplotlib bindings collide with the player/live keys
# (s=save, q=quit, space/p=play, l=loop, arrows/home/end=seek).
for keymap in ("save", "quit", "home", "back", "forward",
"pan", "yscale", "xscale"):
plt.rcParams[f"keymap.{keymap}"] = []
if not self.headless:
plt.ion()
figsize = (13.2, 9.0) if player is not None else (13.2, 8.2)
if self.fast:
self.fig = plt.figure(figsize=figsize)
# In interactive mode every artist update schedules a full canvas
# redraw (Figure.stale -> draw_idle). That is exactly the cost the
# blitting path exists to avoid, so disable the automatic route for
# this figure; the backend's own resize/expose handlers still ask
# for redraws, and update() paints explicitly.
self.fig.stale_callback = None
else:
self.fig = plt.figure(figsize=figsize, constrained_layout=True)
try:
self.fig.canvas.manager.set_window_title("HQ Camera RAW spectrum")
except Exception:
pass
self.fig.suptitle(f"HQ Camera RAW R/G/B spectrum monitor — {description}", fontsize=11)
if player is not None:
gs = self.fig.add_gridspec(
3, 2, width_ratios=(1.18, 1.0),
height_ratios=(1.08, 1.0, 0.17), hspace=0.28,
)
else:
gs = self.fig.add_gridspec(2, 2, width_ratios=(1.18, 1.0),
height_ratios=(1.08, 1.0))
self.ax_preview = self.fig.add_subplot(gs[0, 0])
self.ax_spec = self.fig.add_subplot(gs[0, 1])
self.ax_water = self.fig.add_subplot(gs[1, 0])
self.ax_norm = self.fig.add_subplot(gs[1, 1])
if player is not None:
self._build_player_controls(gs[2, :])
if self.fast:
# constrained_layout re-solves the complete layout (text extents
# included) on every single draw. With a fixed figure size that
# is pure overhead, so reserve the margins once instead.
if player is not None:
self.fig.subplots_adjust(left=0.058, right=0.988,
top=0.938, bottom=0.052)
else:
self.fig.subplots_adjust(left=0.058, right=0.988,
top=0.928, bottom=0.072)
self.im_preview = self.ax_preview.imshow(
np.zeros((2, 2, 3), dtype=np.float32),
extent=(0, self.full_w, self.full_h, 0),
origin="upper",
interpolation="nearest",
aspect="equal",
)
self.ax_preview.set_xlim(0, self.full_w)
self.ax_preview.set_ylim(self.full_h, 0)
self.ax_preview.set_xlabel("sensor x / px")
self.ax_preview.set_ylabel("sensor y / px")
selector_wanted = not self.headless and not args.no_selector
preview_title = ("RAW preview (auto-stretched) — drag a box to set ROI"
if selector_wanted else "RAW preview (auto-stretched) and ROI")
self.ax_preview.set_title(preview_title, fontsize=8.5)
self.roi_patch = self._make_roi_patch(0, 0, 10, 10)
self.ax_preview.add_patch(self.roi_patch)
self.status_text = self.ax_preview.text(
0.012, 0.985, "", transform=self.ax_preview.transAxes,
va="top", ha="left", fontsize=7.1, family="monospace", color="white",
bbox=dict(facecolor="black", alpha=0.58, edgecolor="none", pad=3.5),
zorder=20,
)
# Absolute spectra.
self.raw_lines = {}
self.smooth_lines = {}
for channel in CHANNELS:
(raw_line,) = self.ax_spec.plot([], [], color=CHANNEL_COLORS[channel],
lw=0.55, alpha=0.22)
(smooth_line,) = self.ax_spec.plot([], [], color=CHANNEL_COLORS[channel],
lw=1.55, label=channel)
self.raw_lines[channel] = raw_line
self.smooth_lines[channel] = smooth_line
self.ax_spec.set_title(f"R / G / B profiles: {args.reduce} over ROI rows", fontsize=9)
self.ax_spec.set_ylabel("black-corrected signal / ADU")
self.ax_spec.grid(alpha=0.24)
self.ax_spec.legend(loc="upper right", ncol=3, fontsize=7, framealpha=0.85)
# Normalized spectra + peak markers.
self.norm_lines = {}
self.peak_markers = {}
for channel in CHANNELS:
(line,) = self.ax_norm.plot([], [], color=CHANNEL_COLORS[channel],
lw=1.45, label=channel)
(marker,) = self.ax_norm.plot([], [], linestyle="none", marker="o", ms=3.2,
color=CHANNEL_COLORS[channel], mec="white", mew=0.35)
self.norm_lines[channel] = line
self.peak_markers[channel] = marker
self.ax_norm.set_title("normalized profiles (baseline removed) and peaks", fontsize=9)
self.ax_norm.set_ylabel("normalized")
self.ax_norm.set_ylim(0, 1.08)
self.ax_norm.grid(alpha=0.24)
self.ax_norm.legend(loc="upper right", ncol=3, fontsize=7, framealpha=0.85)
# Waterfall.
waterfall_height = self._wf_rows if self.fast else 2
self.im_water = self.ax_water.imshow(
np.zeros((2, 2), dtype=np.float32),
extent=(0, self.full_w, 0, waterfall_height),
origin="lower", aspect="auto", cmap="inferno", vmin=0.0, vmax=1.0,
interpolation="nearest",
)
self.ax_water.set_title("G-channel waterfall (normalized)", fontsize=9)
self.ax_water.set_ylabel("recent frames (old → new)")
self.ax_water.set_xlim(0, self.full_w)
if self.fast:
# A fixed frame count keeps the axis (and therefore the blitted
# background) stable while the deque fills up.
self.ax_water.set_ylim(0, self._wf_rows)
self.calibration_text = calibration_text
self.ax_norm.set_xlabel(self._xlabel())
self.ax_water.set_xlabel(self._xlabel(), fontsize=8)
if selector_wanted:
from matplotlib.widgets import RectangleSelector
selector_style = dict(facecolor="none", edgecolor="#43d9ff", linewidth=1.1,
linestyle="--", alpha=0.95)
try:
self.selector = RectangleSelector(
self.ax_preview,
self._on_select,
useblit=False,
button=[1],
minspanx=8,
minspany=4,
spancoords="data",
props=selector_style,
)
except TypeError:
# Matplotlib < 3.5 used "rectprops" for the same thing.
self.selector = RectangleSelector(
self.ax_preview,
self._on_select,
useblit=False,
button=[1],
minspanx=8,
minspany=4,
spancoords="data",
rectprops=selector_style,
)
self.fig.canvas.mpl_connect("key_press_event", self._on_key)
self._build_paint_groups()
if self.fast:
self.fig.canvas.mpl_connect("resize_event", self._invalidate_background)
self.fig.canvas.mpl_connect("button_press_event", self._on_button_press)
self.fig.canvas.mpl_connect("button_release_event", self._on_button_release)
if not self.headless:
plt.show(block=False)
# The axes positions are only final after the first layout pass.
self._update_caption()
def _build_paint_groups(self) -> None:
"""Artists that change from frame to frame, grouped by their axes."""
groups: list[tuple] = [
(self.ax_preview, [self.im_preview, self.roi_patch, self.status_text]),
(self.ax_spec, list(self.raw_lines.values()) + list(self.smooth_lines.values())),
(self.ax_norm, list(self.norm_lines.values()) + list(self.peak_markers.values())),
(self.ax_water, [self.im_water]),
]
if self.player is not None:
for button in (self.btn_play, self.btn_start, self.btn_prev,
self.btn_next, self.btn_end, self.btn_loop, self.btn_speed):
if button is not None:
groups.append((button.ax, [button.ax.patch, button.label]))
slider = self.player_slider
if slider is not None:
artists = [getattr(slider, name, None) for name in
("track", "poly", "vline", "_handle", "label", "valtext")]
groups.append((slider.ax, [a for a in artists if a is not None]))
if self.caption is not None:
# Figure-level text above the transport row. It is not clipped to
# an axes, so it is drawn directly into the renderer.
groups.append((None, [self.caption]))
self._paint_groups = groups
def _invalidate_background(self, event=None) -> None:
self._bg = None
def _on_button_press(self, event) -> None:
# RectangleSelector needs a real redraw while the box is being dragged.
if self.fast and event.inaxes is self.ax_preview:
self._force_full = True
def _on_button_release(self, event) -> None:
self._force_full = False
if self.fast:
self._render()
def _view_state(self) -> tuple:
"""Everything that, when changed, requires a full redraw."""
return (
tuple(self.ax_spec.get_xlim()), tuple(self.ax_spec.get_ylim()),
tuple(self.ax_norm.get_xlim()), tuple(self.ax_water.get_xlim()),
tuple(self.ax_water.get_ylim()),
self.ax_norm.get_xlabel(), self.ax_water.get_xlabel(),
)
def _capture_background(self) -> None:
"""Redraw the static parts of the figure and cache them.
The data artists are hidden for this one draw: they are painted on top
of the cached background every frame, so baking them into it would
leave one stale copy of every curve visible for ever (the traces appear
never to be erased).
"""
canvas = self.fig.canvas
hidden = []
for _axes, artists in self._paint_groups:
for artist in artists:
if artist.get_visible():
artist.set_visible(False)
hidden.append(artist)
try:
canvas.draw()
finally:
for artist in hidden:
artist.set_visible(True)
self._bg = canvas.copy_from_bbox(self.fig.bbox)
def _render(self) -> None:
canvas = self.fig.canvas
if not self.fast:
canvas.draw_idle()
return
size = tuple(canvas.get_width_height())
state = self._view_state()
if (self._force_full or self._bg is None or size != self._bg_size
or state != self._bg_state):
self._capture_background()
self._bg_size = size
self._bg_state = state
canvas.restore_region(self._bg)
renderer = None
for axes, artists in self._paint_groups:
for artist in artists:
if axes is None:
# Not clipped to an axes (e.g. the transport caption), so
# it has to go straight into the renderer.
if renderer is None:
renderer = self.fig.canvas.get_renderer()
artist.draw(renderer)
else:
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
def _xlabel(self) -> str:
if "uncalibrated" in self.calibration_text:
return "sensor column / px (uncalibrated)"
return "wavelength / nm"
def _build_player_controls(self, spec) -> None:
from matplotlib.widgets import Button, Slider
player = self.player
if player is None:
return
cg = spec.subgridspec(
1, 8,
width_ratios=(0.78, 0.44, 0.44, 0.44, 0.44, 5.2, 0.95, 0.95),
wspace=0.12,
)
self.ax_play = self.fig.add_subplot(cg[0, 0])
self.ax_start = self.fig.add_subplot(cg[0, 1])
self.ax_prev = self.fig.add_subplot(cg[0, 2])
self.ax_next = self.fig.add_subplot(cg[0, 3])
self.ax_end = self.fig.add_subplot(cg[0, 4])
self.ax_slider = self.fig.add_subplot(cg[0, 5])
self.ax_loop = self.fig.add_subplot(cg[0, 6])
self.ax_speed = self.fig.add_subplot(cg[0, 7])
label_kw = dict(fontsize=7.5, color="#1a1a1a")
self.btn_play = Button(self.ax_play, "Play", color="#dce9ff", hovercolor="#c2d8ff")
self.btn_start = Button(self.ax_start, "|<", color="#eeeeee", hovercolor="#dddddd")
self.btn_prev = Button(self.ax_prev, "<", color="#eeeeee", hovercolor="#dddddd")
self.btn_next = Button(self.ax_next, ">", color="#eeeeee", hovercolor="#dddddd")
self.btn_end = Button(self.ax_end, ">|", color="#eeeeee", hovercolor="#dddddd")
self.btn_loop = Button(self.ax_loop, "Loop: on", color="#eeeeee", hovercolor="#dddddd")
self.btn_speed = Button(self.ax_speed, f"{player.speed:g}x", color="#eeeeee", hovercolor="#dddddd")
for button in (self.btn_play, self.btn_start, self.btn_prev, self.btn_next,
self.btn_end, self.btn_loop, self.btn_speed):
button.label.set_fontsize(label_kw["fontsize"])
button.label.set_color(label_kw["color"])
self.player_slider = Slider(
self.ax_slider, "", 0, max(0, player.total_frames - 1),
valinit=player.current, valstep=1, valfmt="%0.0f",
color="#ffd166", initcolor="none",
)
self.player_slider.valtext.set_visible(False)
# Frame/time caption. A figure-level Text, not an axes title: in the
# blitting path the caption is redrawn every frame, and titles cannot
# be hidden/redrawn independently (hiding any title of the axes hides
# all of them).
self.caption = self.fig.text(0.0, 0.0, "", ha="left", va="bottom", fontsize=7.3)
if self.fast:
# Slider.set_val() asks for a full canvas redraw on every update;
# the blitting path repaints the slider itself instead.
self.player_slider.drawon = False
self._refresh_player(draw=False)
self.btn_play.on_clicked(self._toggle_play)
self.btn_start.on_clicked(lambda event: self._player_seek(0))
self.btn_prev.on_clicked(lambda event: self._player_step(-1))
self.btn_next.on_clicked(lambda event: self._player_step(1))
self.btn_end.on_clicked(lambda event: self._player_seek(player.total_frames - 1))
self.btn_loop.on_clicked(self._toggle_loop)
self.btn_speed.on_clicked(self._cycle_speed)
self.player_slider.on_changed(self._on_player_slider)
def _player_title(self) -> str:
player = self.player
if player is None:
return ""
seconds = player.current / max(player.fps, 0.01)
total_s = player.total_frames / max(player.fps, 0.01)
return (f"frame {player.current + 1}/{player.total_frames} "
f"t={seconds:.2f}s / {total_s:.2f}s")
def _update_caption(self) -> None:
"""Keep the frame/time caption glued just above the transport slider."""
if self.caption is None or self.ax_slider is None:
return
self.caption.set_text(self._player_title())
position = self.ax_slider.get_position()
self.caption.set_position((position.x0 + 0.002, position.y1 + 0.006))
def _refresh_player(self, draw: bool = True) -> None:
player = self.player
if player is None or self.player_slider is None:
return
player.current = max(0, min(player.current, player.total_frames - 1))
self.btn_play.label.set_text("Pause" if player.playing else "Play")
self.btn_loop.label.set_text(f"Loop: {'on' if player.loop else 'off'}")
self.btn_speed.label.set_text(f"{player.speed:g}x")
self._update_caption()
self._player_syncing = True
try:
self.player_slider.set_val(player.current)
finally:
self._player_syncing = False
if draw:
self._render()
def set_player_position(self, frame: int, redraw: bool = True) -> None:
if self.player is None:
return
self.player.current = frame
self._refresh_player(draw=redraw)
def _toggle_play(self, event=None) -> None:
player = self.player
if player is None:
return
if not player.playing and player.current >= player.total_frames - 1:
player.pending_seek = 0
player.playing = not player.playing
if player.playing:
player.needs_reschedule = True
self._refresh_player()
def _player_seek(self, frame: int) -> None:
player = self.player
if player is None:
return
player.playing = False
player.request(frame)
self._refresh_player()
def _player_step(self, delta: int) -> None:
player = self.player
if player is None:
return
self._player_seek(player.current + delta)
def _on_player_slider(self, value) -> None:
if self._player_syncing or self.player is None:
return
player = self.player
player.playing = False
player.pending_seek = max(0, min(player.total_frames - 1, int(round(value))))
self._refresh_player()
def _toggle_loop(self, event=None) -> None:
if self.player is None:
return
self.player.loop = not self.player.loop
self._refresh_player()
def _cycle_speed(self, event=None) -> None:
if self.player is None:
return
speeds = (0.25, 0.5, 1.0, 2.0, 4.0)
current = self.player.speed
try:
index = min(range(len(speeds)), key=lambda i: abs(speeds[i] - current))
except ValueError:
index = 2
self.player.speed = speeds[(index + 1) % len(speeds)]
self.player.needs_reschedule = True
self._refresh_player()
def _make_roi_patch(self, x0: int, y0: int, w: int, h: int):
from matplotlib.patches import Rectangle
return Rectangle((x0, y0), w, h, fill=False, edgecolor="#ffd166",
linewidth=1.5, zorder=15)
def _on_select(self, eclick, erelease) -> None:
if (eclick.xdata is None or erelease.xdata is None or
eclick.ydata is None or erelease.ydata is None or self.on_roi is None):
return
x0, x1 = sorted((eclick.xdata, erelease.xdata))
y0, y1 = sorted((eclick.ydata, erelease.ydata))
roi = make_roi(x0, y0, x1, y1, self.full_w, self.full_h)
if roi.width < 24 or roi.height < 8:
return
self.on_roi(roi)
def _on_key(self, event) -> None:
key = event.key
if key == "s" and self.save_callback is not None:
self.save_callback()
elif key == "q":
# Do not close the canvas here: the main loop still has to save
# the final figure if --save-prefix was given.
self.quit_requested = True
elif self.player is not None:
if key in (" ", "space", "p"):
self._toggle_play()
elif key == "left":
self._player_step(-1)
elif key == "right":
self._player_step(1)
elif key == "home":
self._player_seek(0)
elif key == "end":
self._player_seek(self.player.total_frames - 1)
elif key == "l":
self._toggle_loop()
def _target_y_limits(self, result: SpectrumResult) -> tuple[float, float]:
"""Y range of the absolute spectra; rounded so it seldom changes."""
valid = [v for v in result.signal.values() if v.size]
y_max = max(float(v.max()) for v in valid) if valid else 1.0
return 0.0, _nice_ceiling(max(1.0, y_max * 1.1))
def _update_limits(self, result: SpectrumResult) -> None:
valid_x = [v for v in result.x_plot.values() if v.size]
if valid_x:
x_min = min(float(v.min()) for v in valid_x)
x_max = max(float(v.max()) for v in valid_x)
else:
x_min, x_max = 0.0, float(self.full_w)
if not np.isfinite(x_min) or not np.isfinite(x_max) or x_max <= x_min:
x_min, x_max = 0.0, float(self.full_w)
if tuple(self.ax_spec.get_xlim()) != (x_min, x_max):
self.ax_spec.set_xlim(x_min, x_max)
self.ax_norm.set_xlim(x_min, x_max)
self.ax_water.set_xlim(x_min, x_max)
if self.fast:
self.im_water.set_extent((x_min, x_max, 0, self._wf_rows))
target = self._target_y_limits(result)
current = tuple(self.ax_spec.get_ylim())
# Hysteresis: grow immediately, shrink only when the current range is
# more than ~1.8x larger than needed. Without this the y axis (and
# with it the whole cached background) would change every frame.
if target[1] > current[1] or target[1] * 1.8 < current[1] or target[0] != current[0]:
self.ax_spec.set_ylim(*target)
def _set_waterfall(self, waterfall: np.ndarray, x_min: float, x_max: float) -> None:
if self.fast:
rows = self._wf_rows
width = waterfall.shape[1]
if self._wf_buf is None or self._wf_buf.shape[1] != width:
self._wf_buf = np.zeros((rows, width), dtype=np.float32)
count = min(rows, waterfall.shape[0])
if count < rows:
self._wf_buf[: rows - count] = 0.0
self._wf_buf[rows - count:] = waterfall[-count:]
self.im_water.set_data(self._wf_buf)
else:
self.im_water.set_data(waterfall)
self.im_water.set_extent((x_min, x_max, 0, waterfall.shape[0]))
self.ax_water.set_ylim(0, max(1, waterfall.shape[0]))
def update(self, result: SpectrumResult, waterfall: np.ndarray, fps: float,
status_text: str) -> None:
self.last_result = result
self.im_preview.set_data(result.preview)
self.roi_patch.set_bounds(result.roi.x0, result.roi.y0, result.roi.width, result.roi.height)
self.status_text.set_text(status_text)
for channel in CHANNELS:
x = result.x_plot[channel]
self.raw_lines[channel].set_data(x, result.signal_raw[channel])
self.smooth_lines[channel].set_data(x, result.signal[channel])
self.norm_lines[channel].set_data(x, result.normalized[channel])
idx = result.peaks[channel]
self.peak_markers[channel].set_data(x[idx], result.normalized[channel][idx])
self._update_limits(result)
self.ax_norm.set_xlabel(self._xlabel())
self.ax_water.set_xlabel(self._xlabel(), fontsize=8)
if waterfall.size:
self._set_waterfall(waterfall, *self.ax_spec.get_xlim())
if self.headless:
# Redrawing a full figure for every frame is needlessly expensive
# in a batch/headless run. savefig() at the end draws the final
# state once.
return
self._render()
if not self.fast:
self.fig.canvas.flush_events()
def pump(self, seconds: float, headless: bool) -> None:
if headless:
if seconds > 0:
time.sleep(seconds)
return
if seconds <= 0:
# Nothing to wait for, but the window still has to breathe. While
# the machine is behind schedule the loop must not skip the GUI
# event loop: that is what makes the window freeze ("not
# responding") and swallows clicks on Pause.
self.fig.canvas.flush_events()
return
if self.fast:
# plt.pause() redraws the whole figure as soon as it is marked
# stale, which would throw away the blitted frame; only pump the
# GUI event queue here.
self.fig.canvas.start_event_loop(seconds)
else:
self.plt.pause(seconds)
def save(self, prefix: str) -> tuple[Path, Path]:
if self.last_result is None:
raise RuntimeError("no frame to save yet")
png, csv_path = save_result(self.fig, self.last_result, prefix)
# savefig() renders through its own renderer; drop the cached
# background so the next frame starts from a fresh full draw.
self._bg = None
return png, csv_path
def close(self) -> None:
self.plt.close(self.fig)
# ---------------------------------------------------------------------------
# Save helpers
# ---------------------------------------------------------------------------
def _safe_prefix(prefix: str) -> Path:
path = Path(prefix).expanduser()
if path.suffix.lower() in (".png", ".csv"):
path = path.with_suffix("")
path.parent.mkdir(parents=True, exist_ok=True)
return path
def write_csv(result: SpectrumResult, csv_path: Path) -> Path:
"""Write one profile snapshot; shared by every front end."""
with open(csv_path, "w", newline="", encoding="utf-8") as handle:
handle.write(f"# hq_spectrum snapshot {datetime.now().isoformat(timespec='seconds')}\n")
handle.write(f"# roi={result.roi.text()} size={result.roi.width}x{result.roi.height}\n")
handle.write(f"# raw_format={result.raw_format} bit_depth={result.bit_depth} "
f"black={result.black:g} full_scale={result.full_scale:g}\n")
handle.write(f"# calibration={result.calibration_text}\n")
handle.write(f"# peaks_{result.x_unit}: R={format_peak_values(result, 'R', 5)} "
f"G={format_peak_values(result, 'G', 5)} "
f"B={format_peak_values(result, 'B', 5)}\n")
writer = csv.writer(handle)
writer.writerow(["channel", "x_px", "x_display", "x_unit",
"signal_adu", "signal_smoothed", "normalized"])
for channel in CHANNELS:
x_px = result.x_px[channel]
x_plot = result.x_plot[channel]
n = min(x_px.size, x_plot.size, result.signal_raw[channel].size,
result.signal[channel].size, result.normalized[channel].size)
for i in range(n):
writer.writerow([
channel,
f"{x_px[i]:.3f}",
f"{x_plot[i]:.4f}",
result.x_unit,
f"{result.signal_raw[channel][i]:.3f}",
f"{result.signal[channel][i]:.3f}",
f"{result.normalized[channel][i]:.6f}",
])
return csv_path
def save_result(fig, result: SpectrumResult, prefix: str) -> tuple[Path, Path]:
base = _safe_prefix(prefix)
png_path = base.with_suffix(".png")
csv_path = base.with_suffix(".csv")
fig.savefig(png_path, dpi=150)
write_csv(result, csv_path)
return png_path, csv_path
def top_peak_indices(result: SpectrumResult, channel: str, count: int) -> np.ndarray:
"""Strongest peaks, then returned in left-to-right order for display."""
idx = result.peaks[channel]
if idx.size == 0 or count <= 0:
return np.empty(0, dtype=int)
heights = result.normalized[channel][idx]
chosen = idx[np.argsort(heights)[::-1][:count]]
return chosen[np.argsort(result.x_plot[channel][chosen])]
def format_peak_values(result: SpectrumResult, channel: str, count: int = 1) -> str:
idx = top_peak_indices(result, channel, count)
if not idx.size:
return "—"
return ", ".join(f"{result.x_plot[channel][i]:.1f}" for i in idx)
# ---------------------------------------------------------------------------
# Main loop
# ---------------------------------------------------------------------------
def make_calibration(args: argparse.Namespace) -> Optional[Calibration]:
if not args.calibrate:
return None
pairs: list[tuple[float, float]] = []
for token in args.calibrate.split(","):
token = token.strip()
if not token:
continue
if ":" not in token:
raise ValueError(f"bad calibration token {token!r}; expected PX:NM")
px, nm = token.split(":", 1)
pairs.append((float(px), float(nm)))
if len(pairs) < 2:
raise ValueError("--calibrate needs at least two PX:NM pairs")
return Calibration(pairs, args.poly_order)
def _meta_number(meta: dict, key: str, default: float = 0.0) -> float:
value = meta.get(key, default)
try:
return float(value) if value is not None else default
except (TypeError, ValueError):
return default
def status_for(result: SpectrumResult, fps: float) -> str:
meta = result.metadata
exposure = _meta_number(meta, "ExposureTime")
gain = _meta_number(meta, "AnalogueGain")
fps_text = f"{fps:4.1f}" if fps > 0 else " --"
peaks = {
channel: format_peak_values(result, channel, 3) for channel in CHANNELS
}
frame_line = ""
if "_frame_index" in meta:
frame_line = f"frame {meta['_frame_index']}/{meta.get('_frame_total', '?')}\n"
text = (
f"{result.raw_format} {result.full_size[0]}x{result.full_size[1]} "
f"{result.bit_depth}-bit buf\n"
f"ROI {result.roi.width}x{result.roi.height} @ {result.roi.text()} "
f"{fps_text} fps\n"
f"{frame_line}"
f"exp {exposure / 1000.0:7.2f} ms gain {gain:4.1f} black {result.black:.0f} "
f"sat {result.saturated_fraction * 100.0:.2f}%\n"
f"peaks [{result.x_unit}]\n"
f" R {peaks['R']}\n"
f" G {peaks['G']}\n"
f" B {peaks['B']}"
)
return text
def run_replay_player(args: argparse.Namespace, plt, calibration: Optional[Calibration],
manual_roi: Optional[ROI]) -> int:
"""Interactive player for a recording: play/pause, scrub, step, speed, loop."""
source = None
dashboard = None
state_result: list[Optional[SpectrumResult]] = [None]
saved = False
try:
source = RecordingSource(args.input)
source.start()
if args.exposure is not None or args.gain is not None:
print("note : --exposure/--gain are ignored during replay", file=sys.stderr)
if args.frames:
print("note : --frames is ignored in player mode; use the timeline", file=sys.stderr)
first_raw, first_meta = source.read_at(0)
if manual_roi is not None:
roi = parse_roi(args.roi, *source.full_size)
else:
preview = make_preview(first_raw, source.pattern)
roi = detect_auto_roi(preview, *source.full_size)
if roi is None:
width, height = source.full_size
roi = make_roi(0, 0.30 * height, width, 0.70 * height, width, height)
print("auto ROI: no spectral band found, using full-width central strip")
else:
print(f"auto ROI : {roi.text()} {roi.width}x{roi.height}")
roi_holder = [roi]
first_result = process_frame(
first_raw, first_meta, roi, source.pattern, args, calibration,
source.full_size, source.raw_format, source.bit_depth,
)
state_result[0] = first_result
recorded_fps = float(
source.meta.get("average_capture_fps")
or source.meta.get("fps_requested")
or args.fps
or 15.0
)
if recorded_fps <= 0:
recorded_fps = 15.0
player = PlayerState(
total_frames=source.total_frames,
fps=recorded_fps,
current=0,
playing=bool(args.autoplay),
loop=not args.no_loop,
)
waterfall = deque(maxlen=max(2, int(args.waterfall_rows)))
waterfall.append(first_result.normalized["G"].copy())
dashboard_ref: list[Optional[Dashboard]] = [None]
def on_roi(new_roi: ROI) -> None:
roi_holder[0] = new_roi
waterfall.clear()
player.playing = False
player.pending_seek = player.current
if dashboard_ref[0] is not None:
dashboard_ref[0]._refresh_player()
print(f"ROI changed by mouse: {new_roi.text()} {new_roi.width}x{new_roi.height}")
dashboard = Dashboard(
plt, args, source.full_size, source.description,
first_result.calibration_text, on_roi=on_roi, player=player,
)
dashboard_ref[0] = dashboard
def paint(result: SpectrumResult, fps_now: float) -> None:
wf = np.asarray(waterfall, dtype=np.float32)
if wf.size == 0:
wf = np.zeros((1, 2), dtype=np.float32)
# Move the transport widgets first; update() then repaints the
# whole dashboard (including them) in a single pass.
dashboard.set_player_position(player.current, redraw=False)
dashboard.update(result, wf, fps_now, status_for(result, fps_now))
def do_save(prefix: Optional[str] = None) -> bool:
if dashboard is None or state_result[0] is None:
return False
target = prefix or args.save_prefix
if not target:
target = f"hq_spectrum_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
try:
png, csv_path = dashboard.save(target)
except Exception as exc:
print(f"save failed: {exc}", file=sys.stderr)
return False
print(f"saved: {png}")
print(f"saved: {csv_path}")
return True
dashboard.save_callback = do_save
player.current = 0
paint(first_result, (player.fps * player.speed) if player.playing else 0.0)
next_deadline = time.monotonic() + player.period()
last_play_time = None
play_fps = 0.0
while plt.fignum_exists(dashboard.fig.number):
# Always give the GUI a slice of time, even when the pipeline is
# behind: otherwise the window stops repainting and Pause/keys are
# never delivered until playback ends.
dashboard.pump(0.0, False)
if dashboard.quit_requested:
break
if player.needs_reschedule:
player.needs_reschedule = False
next_deadline = time.monotonic() + player.period()
if player.pending_seek is not None:
target = max(0, min(player.total_frames - 1, int(player.pending_seek)))
player.pending_seek = None
if target != player.current:
waterfall.clear()
raw, meta = source.read_at(target)
result = process_frame(
raw, meta, roi_holder[0], source.pattern, args, calibration,
source.full_size, source.raw_format, source.bit_depth,
)
state_result[0] = result
player.current = target
waterfall.append(result.normalized["G"].copy())
paint(result, 0.0)
next_deadline = time.monotonic() + player.period()
last_play_time = None
continue
if player.playing:
now = time.monotonic()
if now < next_deadline:
dashboard.pump(min(0.05, next_deadline - now), False)
continue
target = source.index
if target >= source.total_frames:
if player.loop:
target = 0
waterfall.clear()
else:
player.playing = False
dashboard._refresh_player()
dashboard.pump(0.05, False)
continue
raw, meta = source.read_at(target)
result = process_frame(
raw, meta, roi_holder[0], source.pattern, args, calibration,
source.full_size, source.raw_format, source.bit_depth,
)
state_result[0] = result
player.current = target
waterfall.append(result.normalized["G"].copy())
now_after = time.monotonic()
if last_play_time is not None:
dt = now_after - last_play_time
if dt > 0:
instant = 1.0 / dt
play_fps = instant if play_fps == 0 else 0.85 * play_fps + 0.15 * instant
last_play_time = now_after
paint(result, play_fps if play_fps > 0 else player.fps * player.speed)
next_deadline += player.period()
if next_deadline < time.monotonic():
# Behind schedule (slow machine): run the next frame
# immediately instead of waiting for a whole extra period.
next_deadline = time.monotonic()
continue
dashboard.pump(0.05, False)
if args.save_prefix and state_result[0] is not None:
saved = do_save(args.save_prefix)
return 0
except KeyboardInterrupt:
print("\ninterrupted")
return 130
except Exception as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
finally:
if args.save_prefix and dashboard is not None and state_result[0] is not None and not saved:
try:
png, csv_path = dashboard.save(args.save_prefix)
print(f"saved: {png}")
print(f"saved: {csv_path}")
except Exception as exc:
print(f"warning: could not save final snapshot: {exc}", file=sys.stderr)
if dashboard is not None:
try:
dashboard.close()
except Exception:
pass
if source is not None:
try:
source.close()
except Exception:
pass
def run(args: argparse.Namespace) -> int:
if args.list_modes:
try:
list_camera_modes()
except Exception as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
return 0
# Import Matplotlib only after the backend has been chosen.
import matplotlib
if args.headless:
matplotlib.use("Agg")
import matplotlib.pyplot as plt
try:
calibration = make_calibration(args)
except ValueError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
try:
manual_roi = parse_roi(args.roi, args.width, args.height)
except ValueError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
if args.input and not args.headless:
return run_replay_player(args, plt, calibration, manual_roi)
source = None
dashboard = None
state: dict = {"roi": manual_roi, "result": None}
saved_on_exit = False
try:
if args.input:
source = RecordingSource(args.input)
elif args.demo:
source = DemoSource(args)
if args.headless and args.frames == 0:
args.frames = 1
else:
source = CameraSource(args)
if args.input and (args.exposure is not None or args.gain is not None):
print("note : --exposure/--gain are ignored during replay", file=sys.stderr)
if manual_roi is not None:
# Re-apply fractions/pixels to the actual raw size (normally the
# same as the requested size, but libcamera is the final authority).
manual_roi = parse_roi(args.roi, *source.full_size)
state["roi"] = manual_roi
print(f"source : {source.description}")
print(f"raw stream : {source.raw_format} {source.full_size[0]}x{source.full_size[1]}")
print(f"stride : {getattr(source, 'stride', 'n/a')}")
print(f"Bayer order : {source.pattern} (decoded {source.bit_depth}-bit buffer)")
if not args.demo and "PISP_COMP" in str(source.raw_format).upper():
print("note : PC1B/PiSP compressed raw is being decompressed in software")
source.start()
# Let AE/AWB and the sensor settle; also fills the first buffers.
# A recording already contains settled frames, so do not skip any.
if getattr(source, "needs_warmup", True):
for _ in range(5):
try:
source.read()
except Exception as exc:
print(f"warning: warm-up read failed: {exc}", file=sys.stderr)
break
roi = state["roi"]
# Headless replay should run as fast as the CPU allows; no point in
# sleeping just to honour a playback frame rate on a batch job.
period = 0.0 if (args.input and args.headless) else 1.0 / max(args.fps, 0.1)
fps_est = 0.0
previous_capture = None
frame_count = 0
capture_error = False
waterfall_rows = max(2, int(args.waterfall_rows))
waterfall = deque(maxlen=waterfall_rows)
last_width = None
def on_roi(new_roi: ROI) -> None:
state["roi"] = new_roi
waterfall.clear()
print(f"ROI changed by mouse: {new_roi.text()} {new_roi.width}x{new_roi.height}")
def do_save(prefix: Optional[str] = None) -> bool:
if dashboard is None or state.get("result") is None:
return False
target = prefix or args.save_prefix
if not target:
target = f"hq_spectrum_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
try:
png, csv_path = dashboard.save(target)
except Exception as exc:
print(f"save failed: {exc}", file=sys.stderr)
return False
print(f"saved: {png}")
print(f"saved: {csv_path}")
return True
while True:
loop_start = time.perf_counter()
try:
raw, metadata = source.read()
except StopIteration:
if (args.input and not args.headless and not args.no_loop and
dashboard is not None and not dashboard.quit_requested):
source.rewind()
waterfall.clear()
last_width = None
previous_capture = None
print("replay : end of recording, looping")
continue
print("replay : end of recording")
break
except KeyboardInterrupt:
raise
except Exception as exc:
print(f"capture error: {exc}", file=sys.stderr)
capture_error = True
break
# Pick up a ROI selected by the mouse in the dashboard.
roi = state["roi"]
if roi is None:
preview = make_preview(raw, source.pattern)
roi = detect_auto_roi(preview, *source.full_size)
if roi is None:
width, height = source.full_size
roi = make_roi(0, 0.30 * height, width, 0.70 * height, width, height)
print("auto ROI: no spectral band found, using full-width central strip")
else:
print(f"auto ROI : {roi.text()} {roi.width}x{roi.height}")
state["roi"] = roi
result = process_frame(
raw, metadata, roi, source.pattern, args, calibration,
source.full_size, source.raw_format, source.bit_depth,
)
state["result"] = result
frame_count += 1
if previous_capture is not None:
dt = time.perf_counter() - previous_capture
if dt > 0:
inst = 1.0 / dt
fps_est = inst if fps_est == 0.0 else 0.90 * fps_est + 0.10 * inst
previous_capture = time.perf_counter()
norm_g = result.normalized["G"]
if last_width is not None and last_width != norm_g.size:
waterfall.clear()
last_width = norm_g.size
waterfall.append(norm_g.copy())
wf = np.asarray(waterfall, dtype=np.float32)
if wf.size == 0:
wf = np.zeros((1, 2), dtype=np.float32)
if dashboard is None:
dashboard = Dashboard(
plt, args, source.full_size, source.description,
result.calibration_text, on_roi=on_roi,
)
dashboard.save_callback = do_save
dashboard.update(result, wf, fps_est, status_for(result, fps_est))
if args.input and (frame_count == 1 or frame_count % 30 == 0):
print(f"analyzing : frame {metadata.get('_frame_index', frame_count)}"
f"/{metadata.get('_frame_total', '?')}")
if args.verbose and frame_count == 1:
print(f"raw range : {int(raw.min())}..{int(raw.max())} "
f"p1={float(np.percentile(raw, 1)):.1f} p99={float(np.percentile(raw, 99)):.1f}")
print(f"black/full : {result.black:.1f}/{result.full_scale:.1f}")
print(f"calibration : {result.calibration_text}")
if args.frames and frame_count >= args.frames:
break
if not args.headless and (dashboard.quit_requested or
not plt.fignum_exists(dashboard.fig.number)):
break
elapsed = time.perf_counter() - loop_start
dashboard.pump(period - elapsed, args.headless)
if args.save_prefix and dashboard is not None and state.get("result") is not None:
saved_on_exit = do_save(args.save_prefix)
elif args.headless and dashboard is not None and state.get("result") is not None and not args.demo:
print("headless run finished; use --save-prefix to write the dashboard and CSV")
return 1 if capture_error else 0
except (RuntimeError, ValueError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
except KeyboardInterrupt:
print("\ninterrupted")
return 130
except Exception as exc:
if args.verbose:
traceback.print_exc()
print(f"error: {exc}", file=sys.stderr)
return 1
finally:
# Save before closing the Matplotlib canvas, otherwise figure.savefig()
# may be operating on a torn-down backend.
if args.save_prefix and dashboard is not None and state.get("result") is not None and not saved_on_exit:
try:
png, csv_path = dashboard.save(args.save_prefix)
print(f"saved: {png}")
print(f"saved: {csv_path}")
except Exception as exc:
print(f"warning: could not save final snapshot: {exc}", file=sys.stderr)
if dashboard is not None:
try:
dashboard.close()
except Exception:
pass
if source is not None:
try:
source.close()
except Exception:
pass
def main(argv: Optional[list[str]] = None) -> int:
args = parse_args(argv)
return run(args)
if __name__ == "__main__":
raise SystemExit(main())