D405 网页采集台:实时预览 + 录制控制 + 下游可用数据格式

- 单文件后端(标准库HTTP) + 单文件前端,依赖仅 pyrealsense2/numpy/opencv-headless
- 可调分辨率/帧率/曝光/增益,定时录制,自定义保存位置
- 输出 color.mp4 + 对齐深度16bit PNG + intrinsics.json(内参/时间戳)
- 拉帧自愈预览与流级自动重启,README 含操作说明与 API

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-15 16:36:08 +08:00
commit af6c04ccb1
5 changed files with 727 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
.venv/
captures/
__pycache__/
*.pyc
nohup.out
+108
View File
@@ -0,0 +1,108 @@
# D405 采集台
Intel RealSense **D405** 深度相机的网页采集工具:浏览器里实时预览彩色+深度画面,
按钮控制录制,输出下游(Dyn-HaMR / 手部重建等)可直接使用的数据格式。
单文件后端(`d405_capture_server.py`,标准库 HTTP 服务)+ 单文件前端(`d405_ui.html`),
无框架依赖。
## 硬件要求
- Intel RealSense D405(其他 RealSense 型号未测;D405 特性:近距 7cm~50cm 最佳,
彩色与深度来自同一对成像器,天然对齐好、曝光联动)
- **USB 3.x 接口**(USB2 带宽不够,高分辨率/帧率会起不来流)
## 依赖与安装
系统 Python 3.12 + venv(**不用 conda**):
```bash
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
```
依赖只有三个(版本为实测可用版本,见 requirements.txt):
| 包 | 用途 |
|---|---|
| `pyrealsense2` 2.58.4 | RealSense SDK Python 绑定,取流/对齐/控曝光 |
| `numpy` | 帧数据处理 |
| `opencv-python-headless` | JPEG/PNG 编码、mp4 写入、深度伪彩(headless 版即可,无 GUI 依赖) |
无需 root、无需安装 librealsense 系统包(pyrealsense2 的 wheel 自带)。
## 运行
```bash
.venv/bin/python d405_capture_server.py # 默认端口 8405
.venv/bin/python d405_capture_server.py --port 9000
```
浏览器打开 **http://localhost:8405**。服务只监听 127.0.0.1,如需远程访问请自行改绑定或做端口转发。
停止/重启(注意 `pkill -f` 会连含同名字符串的当前 shell 一起杀,用带括号的正则排除自身):
```bash
kill $(pgrep -f "d405_captur[e]_server")
```
## 界面操作
左侧实时画面(下方显示当前模式 / 实际帧率 / 深度有效像素比例),右侧四个面板:
1. **录制**
- `● 开始录制 / ■ 停止并保存`
- **录制时长(秒)**:填 N 秒到时自动停止;0 或留空 = 手动停止
- **保存位置**:留空用默认 `captures/`;支持绝对路径和 `~`;相对路径挂在
脚本所在目录下。目录不存在自动创建,每段录制在其下建时间戳子目录
- **保存深度**:关掉可省约 90% 磁盘(深度 PNG 是大头)
2. **视频流**(改动需点「应用」,会重启相机流,约 1 秒黑屏;录制中禁止改)
- 分辨率 424×240 / 640×360 / 848×480 / 1280×720
- 帧率 5 / 15 / 30 / 60 / 90 —— **1280×720 最高 30fps,60/90 需 848×480 及以下**
3. **预览与深度显示**(即时生效):预览 JPEG 画质、深度伪彩范围(0.5/1/2/4m)、
布局(并排 / 仅彩色 / 仅深度)。只影响预览,不影响录制数据
4. **传感器**(即时生效):自动曝光开关;手动模式可调曝光(100~30000µs)与增益
(D405 彩色/深度同一成像器,曝光对两者同时生效)
## 输出格式
每段录制一个目录 `<保存位置>/<YYYYmmdd_HHMMSS>/`:
```
color.mp4 彩色视频,按录制时的分辨率/帧率
depth/000000.png 16bit 单通道 PNG,每帧一张,与 color.mp4 帧号一一对应
intrinsics.json 元数据
```
- 深度 PNG **单位 0.1mm**(值 × depth_scale_m = 米),**已对齐到彩色帧**(rs.align),
与彩色同分辨率,可直接按 intrinsics 反投影成点云
- `intrinsics.json`:对齐后彩色内参(fx/fy/cx/cy)、`depth_scale_m`、录制参数
(分辨率/名义与实际帧率/是否存深度)、`timestamps_ms`(逐帧硬件时间戳,可查丢帧)
## HTTP API(脚本化采集)
| 端点 | 方法 | 说明 |
|---|---|---|
| `/api/status` | GET | 流状态、录制状态、实际 fps、深度有效率 |
| `/api/start` | POST | `{"duration":秒, "save_depth":bool, "out_dir":"路径"}` |
| `/api/stop` | POST | 停止并保存 |
| `/api/config` | POST | 改 `width/height/fps`(触发流重启)或画质/深度范围/曝光等 |
| `/frame.jpg` | GET | 阻塞到**新**一帧再返回(≤1.5s),适合拉帧循环 |
| `/stream` | GET | MJPEG 流(兼容保留,前端已不用) |
示例——命令行录 10 秒到指定目录:
```bash
curl -X POST -d '{"duration":10,"out_dir":"~/datasets/grasp"}' http://localhost:8405/api/start
```
## 设计说明 / 已踩的坑
- **不用 librealsense 原生录制**:SDK ≥2.56 只支持 rosbag2 的 `.db3` 格式,下游不好用,
故自行落 mp4 + PNG + json
- **预览不用 MJPEG 长连接**:连接一断 `<img>` 永远冻在最后一帧要手动刷新。前端改为
`/frame.jpg` 拉帧自愈循环(失败自动重试),服务端「等到新帧才返回」使拉帧节奏
自动对齐相机帧率
- **流级自愈**:`wait_for_frames` 连续超时 2 次自动重启相机流;流启动失败每 2 秒自动重试
- 深度伪彩里黑色 = 无效像素。白墙/无纹理表面、超近(<7cm)或超远处无效点多,
是 D405 立体匹配的正常表现
+345
View File
@@ -0,0 +1,345 @@
#!/usr/bin/env python3
"""D405 采集台:实时预览 + 网页 UI 控制(d405_ui.html)。
http://localhost:8405
可调:分辨率/帧率(重启流)、预览画质、深度显示范围、预览布局、
自动/手动曝光与增益、定时录制、是否保存深度。
录制输出 captures/<时间戳>/:
color.mp4 彩色视频(按当前分辨率/帧率)
depth/%06d.png 16bit 深度 PNG(0.1mm,已对齐彩色;可关)
intrinsics.json 内参 + depth_scale + 逐帧时间戳 + 录制参数
用法: .venv-d405/bin/python d405_capture_server.py [--port 8405]
"""
import argparse, time, threading, datetime, pathlib, json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import numpy as np
import cv2
import pyrealsense2 as rs
HERE = pathlib.Path(__file__).resolve().parent
CAPTURE_ROOT = HERE / "captures"
UI_FILE = HERE / "d405_ui.html"
latest_jpeg = None
frame_seq = 0
frame_lock = threading.Condition()
state_lock = threading.RLock()
cfg = { # 可从 UI 修改
"width": 848, "height": 480, "fps": 30, # 改动需重启流
"jpeg_quality": 80, "depth_max": 1.0, "layout": "side",
"auto_exposure": True, "exposure": 8000, "gain": 64,
}
st = { # 只读状态
"stream_ok": False, "device": "-", "error": "",
"fps_actual": 0.0, "depth_fill": 0.0,
"on": False, "frames": 0, "elapsed": 0.0, "duration": 0,
"last_saved": None,
}
rec = {"dir": None, "writer": None, "timestamps": [], "t0": 0.0,
"save_depth": True}
restart_flag = threading.Event()
sensor_dirty = threading.Event()
intrinsics = {}
def start_recording(duration, save_depth, out_dir=""):
with state_lock:
if st["on"]:
return "已在录制中"
if not st["stream_ok"]:
return "视频流未就绪"
root = CAPTURE_ROOT
if out_dir:
root = pathlib.Path(out_dir).expanduser()
if not root.is_absolute():
root = CAPTURE_ROOT.parent / root # 相对路径挂在 hardware/ 下
try:
root.mkdir(parents=True, exist_ok=True)
probe = root / ".w"
probe.touch(); probe.unlink()
except OSError as e:
return f"保存位置不可写:{root}({e})"
d = root / f"{datetime.datetime.now():%Y%m%d_%H%M%S}"
if save_depth:
(d / "depth").mkdir(parents=True, exist_ok=True)
else:
d.mkdir(parents=True, exist_ok=True)
rec.update(dir=d, timestamps=[], t0=time.time(), save_depth=save_depth,
writer=cv2.VideoWriter(str(d / "color.mp4"),
cv2.VideoWriter_fourcc(*"mp4v"),
cfg["fps"], (cfg["width"], cfg["height"])))
st.update(on=True, frames=0, elapsed=0.0, duration=duration)
print(f"[record] start -> {d} (duration={duration}s, depth={save_depth})",
flush=True)
return None
def stop_recording():
with state_lock:
if not st["on"]:
return
st["on"] = False
rec["writer"].release()
d, n = rec["dir"], st["frames"]
meta = dict(intrinsics)
meta.update(frames=n, width=cfg["width"], height=cfg["height"],
fps_nominal=cfg["fps"],
fps_actual=round(n / max(time.time() - rec["t0"], 1e-6), 2),
save_depth=rec["save_depth"],
timestamps_ms=rec["timestamps"])
(d / "intrinsics.json").write_text(json.dumps(meta, indent=1))
st["last_saved"] = f"{d}({n} 帧)"
print(f"[record] saved {d} ({n} frames)", flush=True)
def apply_sensor_options(profile):
sensor = profile.get_device().first_depth_sensor()
try:
sensor.set_option(rs.option.enable_auto_exposure,
1 if cfg["auto_exposure"] else 0)
if not cfg["auto_exposure"]:
sensor.set_option(rs.option.exposure, float(cfg["exposure"]))
sensor.set_option(rs.option.gain, float(cfg["gain"]))
except Exception as e:
st["error"] = f"曝光设置失败: {e}"
def capture_loop():
global latest_jpeg, frame_seq, intrinsics
while True:
pipe = rs.pipeline()
c = rs.config()
with state_lock:
w, h, fps = cfg["width"], cfg["height"], cfg["fps"]
c.enable_stream(rs.stream.color, w, h, rs.format.bgr8, fps)
c.enable_stream(rs.stream.depth, w, h, rs.format.z16, fps)
try:
profile = pipe.start(c)
except Exception as e:
with state_lock:
st["stream_ok"] = False
st["error"] = f"{w}x{h}@{fps} 启动失败:{e}(2 秒后自动重试)"
print(f"[stream] start failed: {e}, retry in 2s", flush=True)
restart_flag.wait(timeout=2) # 自动重试;UI 改参数可立即触发
restart_flag.clear()
continue
align = rs.align(rs.stream.color)
scale = profile.get_device().first_depth_sensor().get_depth_scale()
dev = profile.get_device()
apply_sensor_options(profile)
frames = align.process(pipe.wait_for_frames())
intr = frames.get_color_frame().profile.as_video_stream_profile().intrinsics
with state_lock:
intrinsics = {"fx": intr.fx, "fy": intr.fy, "cx": intr.ppx,
"cy": intr.ppy, "depth_scale_m": scale,
"aligned_to": "color"}
st.update(stream_ok=True, error="",
device=f"{dev.get_info(rs.camera_info.name)} "
f"#{dev.get_info(rs.camera_info.serial_number)}")
n_win, t_win = 0, time.time()
misses = 0
try:
while not restart_flag.is_set():
if sensor_dirty.is_set():
sensor_dirty.clear()
apply_sensor_options(profile)
try:
raw = pipe.wait_for_frames(5000)
misses = 0
except RuntimeError as e:
misses += 1
print(f"[stream] frame timeout ({misses}): {e}", flush=True)
if misses >= 2: # 连续超时 → 整个流重启
break
continue
frames = align.process(raw)
cf, df = frames.get_color_frame(), frames.get_depth_frame()
color = np.asanyarray(cf.get_data())
depth_raw = np.asanyarray(df.get_data())
with state_lock:
if st["on"]:
rec["writer"].write(color)
if rec["save_depth"]:
cv2.imwrite(str(rec["dir"] / "depth" /
f"{st['frames']:06d}.png"), depth_raw)
rec["timestamps"].append(cf.get_timestamp())
st["frames"] += 1
st["elapsed"] = time.time() - rec["t0"]
if st["duration"] > 0 and st["elapsed"] >= st["duration"]:
stop_recording()
recording, nrec, el = st["on"], st["frames"], st["elapsed"]
q, dmax, layout = (cfg["jpeg_quality"], cfg["depth_max"],
cfg["layout"])
# 统计
n_win += 1
now = time.time()
if now - t_win >= 1.0:
with state_lock:
st["fps_actual"] = n_win / (now - t_win)
st["depth_fill"] = 100.0 * np.count_nonzero(depth_raw) \
/ depth_raw.size
n_win, t_win = 0, now
# 预览合成
panels = []
if layout in ("side", "color"):
panels.append(color)
if layout in ("side", "depth"):
dm = np.clip(depth_raw.astype(np.float32) * scale, 0, dmax)
vis = cv2.applyColorMap((dm / dmax * 255).astype(np.uint8),
cv2.COLORMAP_TURBO)
vis[depth_raw == 0] = 0
panels.append(vis)
combo = np.hstack(panels) if len(panels) > 1 else panels[0]
label = f"{datetime.datetime.now():%H:%M:%S}"
if recording:
label += f" REC {nrec} f {el:.0f}s"
cv2.circle(combo, (12, 14), 6, (0, 0, 255), -1)
cv2.putText(combo, label, (24, 20), cv2.FONT_HERSHEY_SIMPLEX,
0.55, (0, 0, 255) if recording else (255, 255, 255), 1)
ok, jpg = cv2.imencode(".jpg", combo,
[cv2.IMWRITE_JPEG_QUALITY, q])
if ok:
with frame_lock:
latest_jpeg = jpg.tobytes()
frame_seq += 1
frame_lock.notify_all()
finally:
stop_recording()
with state_lock:
st["stream_ok"] = False
pipe.stop()
restart_flag.clear()
class Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _json(self, obj, code=200):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def _body(self):
n = int(self.headers.get("Content-Length") or 0)
return json.loads(self.rfile.read(n) or b"{}")
def do_POST(self):
if self.path == "/api/start":
b = self._body()
err = start_recording(int(b.get("duration", 0)),
bool(b.get("save_depth", True)),
str(b.get("out_dir", "")).strip())
self._json({"ok": err is None, "error": err})
elif self.path == "/api/stop":
stop_recording()
self._json({"ok": True})
elif self.path == "/api/config":
b = self._body()
need_restart = False
with state_lock:
for k in ("width", "height", "fps"):
if k in b and int(b[k]) != cfg[k]:
if st["on"]:
self._json({"error": "录制中不能改视频流参数"})
return
cfg[k] = int(b[k])
need_restart = True
for k in ("jpeg_quality", "exposure", "gain"):
if k in b:
cfg[k] = int(b[k])
if "depth_max" in b:
cfg["depth_max"] = float(b["depth_max"])
if "layout" in b:
cfg["layout"] = str(b["layout"])
if "auto_exposure" in b:
cfg["auto_exposure"] = bool(b["auto_exposure"])
st["error"] = ""
if need_restart:
restart_flag.set()
deadline = time.time() + 8
while time.time() < deadline:
time.sleep(0.2)
with state_lock:
if st["stream_ok"]:
break
if st["error"]:
self._json({"error": st["error"]})
return
with state_lock:
self._json({"ok": st["stream_ok"],
"error": st["error"] or None})
else:
sensor_dirty.set()
self._json({"ok": True})
else:
self.send_error(404)
def do_GET(self):
if self.path == "/":
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(UI_FILE.read_bytes())
elif self.path == "/api/status":
with state_lock:
out = dict(st)
out.update(width=cfg["width"], height=cfg["height"],
fps=cfg["fps"])
out.pop("timestamps", None)
self._json(out)
elif self.path.startswith("/frame.jpg"):
# 等到「新」一帧再返回(最多 1.5s),前端拉帧循环靠它对齐相机节奏
with frame_lock:
seq0 = frame_seq
frame_lock.wait_for(lambda: frame_seq != seq0, timeout=1.5)
buf = latest_jpeg
if buf is None:
self.send_error(503, "no frame yet")
return
self.send_response(200)
self.send_header("Content-Type", "image/jpeg")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(buf)))
self.end_headers()
try:
self.wfile.write(buf)
except (BrokenPipeError, ConnectionResetError):
pass
elif self.path.startswith("/stream"):
# 兼容保留的 MJPEG 端点(UI 已改用 /frame.jpg 拉帧自愈)
self.send_response(200)
self.send_header("Content-Type",
"multipart/x-mixed-replace; boundary=f")
self.end_headers()
try:
while True:
with frame_lock:
frame_lock.wait(timeout=2)
buf = latest_jpeg
if buf is None:
continue
self.wfile.write(b"--f\r\nContent-Type: image/jpeg\r\n\r\n"
+ buf + b"\r\n")
except (BrokenPipeError, ConnectionResetError):
pass
else:
self.send_error(404)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8405)
args = ap.parse_args()
threading.Thread(target=capture_loop, daemon=True).start()
print(f"[live] http://localhost:{args.port}", flush=True)
ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever()
+266
View File
@@ -0,0 +1,266 @@
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>D405 采集台</title>
<style>
:root{
--bg:#101418; --panel:#1a2027; --line:#2a323c; --txt:#dde3ea; --dim:#8a95a3;
--acc:#3d9df0; --rec:#e0453a;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--txt);
font:14px/1.5 system-ui,"Noto Sans CJK SC",sans-serif}
header{display:flex;align-items:center;gap:14px;padding:10px 18px;
border-bottom:1px solid var(--line)}
header h1{font-size:16px;margin:0;font-weight:600}
#conn{font-size:12px;color:var(--dim)}
#conn.bad{color:var(--rec)}
main{display:flex;gap:14px;padding:14px;align-items:flex-start;flex-wrap:wrap}
#viewwrap{flex:1 1 640px;min-width:320px}
#view{width:100%;display:block;background:#000;border:1px solid var(--line);
border-radius:8px;min-height:200px}
#overlay{display:flex;gap:16px;margin-top:6px;font-size:13px;color:var(--dim)}
aside{width:300px;flex:0 0 300px;display:flex;flex-direction:column;gap:12px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;
padding:12px 14px}
.card h2{margin:0 0 10px;font-size:13px;color:var(--dim);font-weight:600;
text-transform:none;letter-spacing:.5px}
.row{display:flex;align-items:center;justify-content:space-between;
gap:10px;margin:8px 0}
.row label{color:var(--txt)}
select,input[type=number]{background:#12171d;color:var(--txt);
border:1px solid var(--line);border-radius:6px;padding:5px 8px;width:130px}
input[type=range]{width:130px;accent-color:var(--acc)}
input[type=checkbox]{width:16px;height:16px;accent-color:var(--acc)}
.val{color:var(--dim);font-size:12px;min-width:38px;text-align:right}
button{border:0;border-radius:8px;padding:10px 0;width:100%;font-size:16px;
font-weight:600;cursor:pointer;transition:background .15s}
#recbtn{background:var(--acc);color:#fff}
#recbtn.rec{background:var(--rec)}
#recbtn:disabled{background:#333;color:#777;cursor:not-allowed}
#applybtn{background:#2a323c;color:var(--txt);font-size:14px;padding:8px 0}
#applybtn.dirty{background:#c98a1b;color:#fff}
#recinfo{margin-top:8px;font-size:13px;color:var(--dim);min-height:20px}
#recinfo b{color:var(--txt)}
#saved{font-size:12px;color:var(--dim);margin-top:4px;word-break:break-all}
#msg{font-size:12px;color:var(--rec);min-height:16px;margin-top:6px}
.hint{font-size:11px;color:var(--dim);margin-top:2px}
</style>
</head>
<body>
<header>
<h1>📷 D405 采集台</h1>
<span id="conn">连接中…</span>
</header>
<main>
<div id="viewwrap">
<img id="view" alt="live">
<div id="overlay">
<span id="ov_mode">—</span><span id="ov_fps">—</span><span id="ov_depth">—</span>
</div>
</div>
<aside>
<div class="card">
<h2>录制</h2>
<button id="recbtn" onclick="toggleRec()">● 开始录制</button>
<div class="row">
<label>录制时长(秒)</label>
<input type="number" id="duration" min="0" max="86400" step="1" value="0"
style="width:80px">
</div>
<div class="hint">0 = 手动停止;填 N 秒到时自动停止保存</div>
<div class="row">
<label>保存位置</label>
<input type="text" id="out_dir" style="width:170px"
placeholder="默认 hardware/captures">
</div>
<div class="hint">目录不存在会自动创建,~ 可用;每段录制在其下建时间戳子目录</div>
<div class="row">
<label>保存深度</label>
<input type="checkbox" id="save_depth" checked>
</div>
<div id="recinfo"></div>
<div id="saved"></div>
</div>
<div class="card">
<h2>视频流(改动需应用,会重启流)</h2>
<div class="row">
<label>分辨率</label>
<select id="res">
<option value="1280x720">1280×720</option>
<option value="848x480" selected>848×480</option>
<option value="640x360">640×360</option>
<option value="424x240">424×240</option>
</select>
</div>
<div class="row">
<label>帧率</label>
<select id="fps">
<option>5</option><option>15</option><option selected>30</option>
<option>60</option><option>90</option>
</select>
</div>
<div class="hint">1280×720 最高 30fps;60/90fps 需 848×480 及以下</div>
<button id="applybtn" onclick="applyStream()">应用视频流设置</button>
</div>
<div class="card">
<h2>预览与深度显示(即时生效)</h2>
<div class="row">
<label>预览画质</label>
<input type="range" id="quality" min="30" max="95" step="5" value="80">
<span class="val" id="quality_v">80</span>
</div>
<div class="row">
<label>深度范围</label>
<select id="depth_max">
<option value="0.5">0 ~ 0.5 m</option>
<option value="1" selected>0 ~ 1 m</option>
<option value="2">0 ~ 2 m</option>
<option value="4">0 ~ 4 m</option>
</select>
</div>
<div class="row">
<label>预览布局</label>
<select id="layout">
<option value="side" selected>彩色 | 深度</option>
<option value="color">仅彩色</option>
<option value="depth">仅深度</option>
</select>
</div>
</div>
<div class="card">
<h2>传感器(即时生效)</h2>
<div class="row">
<label>自动曝光</label>
<input type="checkbox" id="auto_exp" checked>
</div>
<div class="row">
<label>手动曝光 µs</label>
<input type="range" id="exposure" min="100" max="30000" step="100" value="8000" disabled>
<span class="val" id="exposure_v">8000</span>
</div>
<div class="row">
<label>增益</label>
<input type="range" id="gain" min="16" max="248" step="8" value="64" disabled>
<span class="val" id="gain_v">64</span>
</div>
</div>
<div id="msg"></div>
</aside>
</main>
<script>
const $ = id => document.getElementById(id);
let st = {on:false}, streamDirty = false;
// ---- 自愈式拉帧预览:/frame.jpg 服务端等新帧才返回,断了自动重连 ----
const sleep = ms => new Promise(r=>setTimeout(r,ms));
let lastUrl = null;
(async function frameLoop(){
for(;;){
try{
const r = await fetch('/frame.jpg', {cache:'no-store'});
if(!r.ok) throw 0;
const url = URL.createObjectURL(await r.blob());
$('view').src = url;
if(lastUrl) URL.revokeObjectURL(lastUrl);
lastUrl = url;
}catch(e){
await sleep(700); // 服务端重启视频流期间在此重试
}
}
})();
async function api(path, body){
const r = await fetch(path, body===undefined ? {} :
{method:'POST', headers:{'Content-Type':'application/json'},
body:JSON.stringify(body)});
return r.json();
}
// ---- 即时生效项 ----
function pushLive(){
api('/api/config', {
jpeg_quality:+$('quality').value,
depth_max:+$('depth_max').value,
layout:$('layout').value,
auto_exposure:$('auto_exp').checked,
exposure:+$('exposure').value,
gain:+$('gain').value,
}).catch(()=>{});
}
['depth_max','layout'].forEach(id=>$(id).onchange=pushLive);
$('quality').oninput=()=>{$('quality_v').textContent=$('quality').value};
$('quality').onchange=pushLive;
$('exposure').oninput=()=>{$('exposure_v').textContent=$('exposure').value};
$('exposure').onchange=pushLive;
$('gain').oninput=()=>{$('gain_v').textContent=$('gain').value};
$('gain').onchange=pushLive;
$('auto_exp').onchange=()=>{
const manual=!$('auto_exp').checked;
$('exposure').disabled=!manual; $('gain').disabled=!manual;
pushLive();
};
// ---- 视频流设置(需重启)----
$('res').onchange=$('fps').onchange=()=>{
streamDirty=true;
$('applybtn').classList.add('dirty');
$('applybtn').textContent='应用视频流设置(未生效)';
};
async function applyStream(){
const [w,h]=$('res').value.split('x').map(Number);
$('applybtn').textContent='重启视频流中…';
const r=await api('/api/config',{width:w,height:h,fps:+$('fps').value});
streamDirty=false;
$('applybtn').classList.remove('dirty');
$('applybtn').textContent='应用视频流设置';
$('msg').textContent=r.error||'';
}
// ---- 录制 ----
async function toggleRec(){
if(st.on){ await api('/api/stop',{}); }
else{
const r=await api('/api/start',{
duration:+$('duration').value||0,
out_dir:$('out_dir').value.trim(),
save_depth:$('save_depth').checked});
$('msg').textContent=r.error||'';
}
poll();
}
// ---- 状态轮询 ----
async function poll(){
try{
st=await api('/api/status');
$('conn').textContent='已连接 · '+st.device;
$('conn').className='';
}catch(e){
$('conn').textContent='连接断开';
$('conn').className='bad';
return;
}
const b=$('recbtn');
b.disabled=!st.stream_ok;
if(st.on){
b.textContent='■ 停止并保存'; b.classList.add('rec');
let t=`录制中:<b>${st.frames}</b> 帧 · ${st.elapsed.toFixed(0)}s`;
if(st.duration>0) t+=` / ${st.duration}s(自动停止)`;
$('recinfo').innerHTML=t;
}else{
b.textContent='● 开始录制'; b.classList.remove('rec');
$('recinfo').innerHTML='';
}
$('saved').textContent=st.last_saved?('上次保存:'+st.last_saved):'';
$('ov_mode').textContent=`${st.width}×${st.height}@${st.fps}`;
$('ov_fps').textContent=`实际 ${st.fps_actual.toFixed(1)} fps`;
$('ov_depth').textContent=`深度有效 ${st.depth_fill.toFixed(0)}%`;
if(st.error) $('msg').textContent=st.error;
}
setInterval(poll,1000); poll();
</script>
</body>
</html>
+3
View File
@@ -0,0 +1,3 @@
pyrealsense2==2.58.4.10922
numpy==2.5.3
opencv-python-headless==5.0.0.93