旧默认指向已删除的 Programs/wavelength_calibration/,不指定就直接报错。 现在先按录制名 + 帧号找,找不到再唯一匹配,仍找不到才提示传 --calibration。
158 lines
7.4 KiB
Python
158 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Replay hq_record RAW recordings with saved wavelength calibration.
|
|
|
|
Keep next to hq_spectrum.py and spectro_core.py. All original playback switches
|
|
are supported.
|
|
"""
|
|
from __future__ import annotations
|
|
import argparse
|
|
from contextlib import redirect_stdout
|
|
import io
|
|
from pathlib import Path
|
|
import sys
|
|
|
|
import numpy as np
|
|
|
|
try: # shared core lives beside this script
|
|
import spectro_core as core
|
|
except ImportError as exc: # pragma: no cover - placement error
|
|
raise SystemExit('wavelength_player.py needs spectro_core.py in the same directory '
|
|
'(or on sys.path)') from exc
|
|
|
|
# Kept as the historical name: the player validates a saved calibration exactly
|
|
# like every other tool now does.
|
|
SavedCalibration = core.Calibration
|
|
|
|
|
|
def load_player():
|
|
# A private module instance provides hooks without editing the original file.
|
|
return core.load_hq()
|
|
|
|
|
|
def install_hooks(hq, calibration):
|
|
original_process = hq.process_frame
|
|
|
|
def process(raw, meta, roi, pattern, args, model, full_size, raw_format, bit_depth):
|
|
result = original_process(raw, meta, roi, pattern, args, model, full_size, raw_format, bit_depth)
|
|
# Retain signed black-subtracted ADU; normalized copies are detection only.
|
|
planes = hq.extract_planes(raw, pattern, roi)
|
|
for c in hq.CHANNELS:
|
|
values = (np.median(planes[c], axis=0) if args.reduce == 'median'
|
|
else np.mean(planes[c], axis=0, dtype=np.float64)) - result.black
|
|
values = values[:len(result.x_px[c])]
|
|
positive = np.maximum(values, 0)
|
|
norm = positive / positive.max() if positive.size and positive.max() > 0 else np.zeros_like(values)
|
|
result.signal_raw[c] = values
|
|
result.signal[c] = values.copy()
|
|
result.normalized[c] = norm
|
|
result.peaks[c] = hq.find_peaks_normalized(norm, result.x_px[c],
|
|
max(1, int(np.ceil(args.peak_distance / 2))), args.peak_prominence,
|
|
args.peak_height, args.max_peaks)
|
|
return result
|
|
|
|
class CalibratedDashboard(hq.Dashboard):
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.ax_norm.set_title('Normalized profiles (detection only; no smoothing)', fontsize=9)
|
|
for axis in (self.ax_spec, self.ax_norm, self.ax_water):
|
|
axis.axvspan(*calibration.nm_span, alpha=.08, color='green', zorder=0)
|
|
|
|
def update(self, result, waterfall, fps, status_text):
|
|
# imshow needs an equally spaced nm grid, including quadratic/reverse mappings.
|
|
if waterfall.size:
|
|
gx = result.x_plot['G']
|
|
xmin = min(float(x.min()) for x in result.x_plot.values())
|
|
xmax = max(float(x.max()) for x in result.x_plot.values())
|
|
grid = np.linspace(xmin, xmax, waterfall.shape[1])
|
|
order = np.argsort(gx)
|
|
waterfall = np.asarray([np.interp(grid, gx[order], row[order]) for row in waterfall])
|
|
super().update(result, waterfall, fps, status_text)
|
|
|
|
def _target_y_limits(self, result):
|
|
# Signed signal (black already subtracted) can dip below zero, so the
|
|
# range is padded; rounding and hysteresis happen in Dashboard, which
|
|
# keeps the cached background valid instead of redrawing every frame.
|
|
valid = [v for v in result.signal.values() if v.size]
|
|
ymin = min(float(v.min()) for v in valid) if valid else 0.0
|
|
ymax = max(float(v.max()) for v in valid) if valid else 1.0
|
|
pad = max(1.0, (ymax - ymin) * 0.05)
|
|
return (hq._nice_floor(min(0.0, ymin - pad)),
|
|
hq._nice_ceiling(max(1.0, ymax + pad)))
|
|
|
|
hq.process_frame = process
|
|
hq.Dashboard = CalibratedDashboard
|
|
hq.make_calibration = lambda args: calibration
|
|
|
|
|
|
def default_calibration(input_dir, frame: int = 0):
|
|
"""Look for the calibration peak_finder/wavelength_calibration just wrote."""
|
|
|
|
root = Path.cwd() / 'calibration_exports'
|
|
if not root.is_dir():
|
|
return None
|
|
stem = Path(input_dir).name
|
|
exact = root / f'{stem}_f{frame:04d}' / 'calibration.json'
|
|
if exact.is_file():
|
|
return str(exact)
|
|
matches = sorted(root.glob(f'{stem}_f*/calibration.json'))
|
|
return str(matches[0]) if len(matches) == 1 else None
|
|
|
|
|
|
def main(argv=None):
|
|
argv = sys.argv[1:] if argv is None else list(argv)
|
|
options = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
|
|
options.add_argument('--calibration', default=None)
|
|
extra, rest = options.parse_known_args(argv)
|
|
try:
|
|
hq = load_player()
|
|
if '-h' in rest or '--help' in rest:
|
|
print('Wavelength recording player: wavelength_player.py --input REC_DIR --calibration calibration.json')
|
|
print('--calibration: saved JSON; --roi calibration: use saved ROI; default ROI is auto.')
|
|
print('No smoothing. Original player options follow:\n')
|
|
buffer = io.StringIO()
|
|
with redirect_stdout(buffer):
|
|
try:
|
|
hq.parse_args(['--help'])
|
|
except SystemExit:
|
|
pass
|
|
print(buffer.getvalue().replace('(default: 3)', '(default: 1)').replace(
|
|
'Live R/G/B spectral analysis of Raspberry Pi HQ Camera RAW frames.',
|
|
'Saved-calibration playback of HQ Camera RAW recordings.'))
|
|
print('Only recording playback is supported; --demo, --list-modes, --calibrate are unavailable.')
|
|
return 0
|
|
args = hq.parse_args(['--smooth', '1'] + rest)
|
|
if not args.input or args.demo or args.list_modes or args.calibrate:
|
|
raise ValueError('use --input REC_DIR and --calibration JSON; live/demo/--calibrate are unsupported')
|
|
if args.smooth != 1:
|
|
raise ValueError('this player preserves unsmoothed signal; --smooth must be 1')
|
|
if extra.calibration is None:
|
|
extra.calibration = default_calibration(args.input, getattr(args, 'frame', 0) or 0)
|
|
if extra.calibration is None:
|
|
raise ValueError(
|
|
'no calibration given; pass --calibration PATH '
|
|
'(e.g. calibration_exports/<recording>_f0001/calibration.json)')
|
|
calibration = SavedCalibration(extra.calibration)
|
|
source = hq.RecordingSource(args.input)
|
|
calibration.validate_geometry(source)
|
|
args.width, args.height = source.full_size
|
|
if args.roi == 'calibration':
|
|
roi = calibration.data['roi']
|
|
if len(roi) != 4 or any(not np.isfinite(float(v)) for v in roi):
|
|
raise ValueError('invalid saved ROI')
|
|
args.roi = ','.join(str(v) for v in roi)
|
|
print('Calibration:', calibration.path)
|
|
print('Descending coefficients:', calibration.coeff.tolist())
|
|
print(calibration.describe())
|
|
print('Use unchanged optics and sensor mode; each recording supplies its own black level.')
|
|
if args.headless and not args.frames:
|
|
print('Headless mode: processing all frames; use --frames N for a shorter run.')
|
|
install_hooks(hq, calibration)
|
|
return hq.run(args)
|
|
except (ValueError, KeyError, TypeError, OSError, RuntimeError) as exc:
|
|
print(f'Player error: {exc}', file=sys.stderr)
|
|
return 2
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|