时间戳治理 + 工作距离/健康度指示 + 低分辨率提醒
- 禁用 librealsense global_time_enabled,时间戳改走相机硬件时钟(hardware_clock), 消除软件对时造成的 ~150ms 回跳(旧录制 424×240@60 第 575 帧实测 −149ms) - intrinsics.json 逐帧记录彩色/深度双流硬件时间戳、帧号、主机到达时刻, 以及本段丢帧数与时间戳回跳数;README 补字段表与坑 - /api/status 增加中心距离 dist_cm(中央 1/3 区域深度中位数)与 drops/backjumps - UI 状态栏:中心距离按 D405 最佳 7–50cm 变色提示;录制健康度实时显示; 分辨率低于 848×480 时提示指尖/指缝细节风险;首次连接同步服务端流参数 - 实测 424×240@60:600 帧与 3595 帧两段均零丢帧零回跳,间隔恒定 16.697ms, 彩色-深度时间戳差 <0.33ms Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
@@ -48,7 +48,10 @@ kill $(pgrep -f "d405_captur[e]_server")
|
||||
|
||||
## 界面操作
|
||||
|
||||
左侧实时画面(下方显示当前模式 / 实际帧率 / 深度有效像素比例),右侧四个面板:
|
||||
左侧实时画面,下方状态栏依次显示:当前模式 / 实际帧率 / 深度有效像素比例 /
|
||||
**中心距离**(画面中央 1/3 区域深度中位数,D405 最佳工作距离 7–50cm,超出变红提示
|
||||
太近或太远)/ **录制健康度**(丢帧数与时间戳回跳数,录制中实时刷新,停止后保留上一段的
|
||||
统计,非 0 变红)。右侧四个面板:
|
||||
|
||||
1. **录制**
|
||||
- `● 开始录制 / ■ 停止并保存`
|
||||
@@ -59,6 +62,8 @@ kill $(pgrep -f "d405_captur[e]_server")
|
||||
2. **视频流**(改动需点「应用」,会重启相机流,约 1 秒黑屏;录制中禁止改)
|
||||
- 分辨率 424×240 / 640×360 / 848×480 / 1280×720
|
||||
- 帧率 5 / 15 / 30 / 60 / 90 —— **1280×720 最高 30fps,60/90 需 848×480 及以下**
|
||||
- 选 848×480 以下时面板会提示:低分辨率对手腕/手掌整体定位可用,但指尖、指缝和
|
||||
遮挡边界容易出错;手部重建建议 ≥848×480,且手和物体处在 7–50cm 内
|
||||
3. **预览与深度显示**(即时生效):预览 JPEG 画质、深度伪彩范围(0.5/1/2/4m)、
|
||||
布局(并排 / 仅彩色 / 仅深度)。只影响预览,不影响录制数据
|
||||
4. **传感器**(即时生效):自动曝光开关;手动模式可调曝光(100~30000µs)与增益
|
||||
@@ -77,13 +82,24 @@ intrinsics.json 元数据
|
||||
- 深度 PNG **单位 0.1mm**(值 × depth_scale_m = 米),**已对齐到彩色帧**(rs.align),
|
||||
与彩色同分辨率,可直接按 intrinsics 反投影成点云
|
||||
- `intrinsics.json`:对齐后彩色内参(fx/fy/cx/cy)、`depth_scale_m`、录制参数
|
||||
(分辨率/名义与实际帧率/是否存深度)、`timestamps_ms`(逐帧硬件时间戳,可查丢帧)
|
||||
(分辨率/名义与实际帧率/是否存深度),以及逐帧时间信息(各列等长、按帧对齐):
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
| `time_source` / `timestamp_domain` | 时间来源说明;域应为 `hardware_clock`(相机硬件时钟,单调) |
|
||||
| `timestamps_ms` | 彩色帧硬件时间戳(ms)。**可直接用于速度/加速度计算** |
|
||||
| `depth_timestamps_ms` | 深度帧硬件时间戳(ms),与彩色差 <0.5ms(同一次曝光) |
|
||||
| `color_frame_numbers` / `depth_frame_numbers` | 相机侧帧号(两流计数器独立,各自连续即无丢帧) |
|
||||
| `host_arrival_monotonic_ns` | 主机 `monotonic_ns` 到达时刻,仅用于和其他主机设备粗对时(抖动 5~40ms,不要拿它算运动) |
|
||||
| `dropped_frames` / `timestamp_backjumps` | 本段录制丢帧数 / 时间戳非单调次数,**下游用前先看这两项是否为 0** |
|
||||
|
||||
彩色与深度每行来自同一 frameset;D405 的彩色取自左成像器,和深度同一次曝光,属硬件级同步。
|
||||
|
||||
## HTTP API(脚本化采集)
|
||||
|
||||
| 端点 | 方法 | 说明 |
|
||||
|---|---|---|
|
||||
| `/api/status` | GET | 流状态、录制状态、实际 fps、深度有效率 |
|
||||
| `/api/status` | GET | 流状态、录制状态、实际 fps、深度有效率、中心距离 `dist_cm`、本段丢帧 `drops` / 回跳 `backjumps` |
|
||||
| `/api/start` | POST | `{"duration":秒, "save_depth":bool, "out_dir":"路径"}` |
|
||||
| `/api/stop` | POST | 停止并保存 |
|
||||
| `/api/config` | POST | 改 `width/height/fps`(触发流重启)或画质/深度范围/曝光等 |
|
||||
@@ -104,5 +120,10 @@ curl -X POST -d '{"duration":10,"out_dir":"~/datasets/grasp"}' http://localhost:
|
||||
`/frame.jpg` 拉帧自愈循环(失败自动重试),服务端「等到新帧才返回」使拉帧节奏
|
||||
自动对齐相机帧率
|
||||
- **流级自愈**:`wait_for_frames` 连续超时 2 次自动重启相机流;流启动失败每 2 秒自动重试
|
||||
- **时间戳必须关掉 librealsense 的 `global_time_enabled`**:它默认开启,用软件线性回归把
|
||||
相机时钟对到主机时钟,回归更新时时间戳会**回跳**(实测 424×240@60 录 600 帧出现一次
|
||||
−149ms),这种数据不能算速度/加速度。关掉后时间戳域变为 `hardware_clock`,实测 600 帧
|
||||
间隔恒定 16.697ms、零回跳。代价是时间戳零点是相机上电时刻,不是 epoch——跨设备对时
|
||||
用 `host_arrival_monotonic_ns` 粗配即可
|
||||
- 深度伪彩里黑色 = 无效像素。白墙/无纹理表面、超近(<7cm)或超远处无效点多,
|
||||
是 D405 立体匹配的正常表现
|
||||
|
||||
+50
-9
@@ -7,7 +7,7 @@ http://localhost:8405
|
||||
录制输出 captures/<时间戳>/:
|
||||
color.mp4 彩色视频(按当前分辨率/帧率)
|
||||
depth/%06d.png 16bit 深度 PNG(0.1mm,已对齐彩色;可关)
|
||||
intrinsics.json 内参 + depth_scale + 逐帧时间戳 + 录制参数
|
||||
intrinsics.json 内参 + depth_scale + 逐帧双流硬件时间戳/帧号 + 丢帧统计 + 录制参数
|
||||
|
||||
用法: .venv-d405/bin/python d405_capture_server.py [--port 8405]
|
||||
"""
|
||||
@@ -34,12 +34,16 @@ cfg = { # 可从 UI 修改
|
||||
}
|
||||
st = { # 只读状态
|
||||
"stream_ok": False, "device": "-", "error": "",
|
||||
"fps_actual": 0.0, "depth_fill": 0.0,
|
||||
"fps_actual": 0.0, "depth_fill": 0.0, "dist_cm": 0.0,
|
||||
"on": False, "frames": 0, "elapsed": 0.0, "duration": 0,
|
||||
"drops": 0, "backjumps": 0,
|
||||
"last_saved": None,
|
||||
}
|
||||
rec = {"dir": None, "writer": None, "timestamps": [], "t0": 0.0,
|
||||
"save_depth": True}
|
||||
rec = {"dir": None, "writer": None, "t0": 0.0, "save_depth": True,
|
||||
# 逐帧时间记录:双流硬件时间戳 + 帧号 + 主机单调钟到达时刻
|
||||
"color_ts": [], "depth_ts": [], "color_fn": [], "depth_fn": [],
|
||||
"arrival_ns": [], "prev_cts": None, "prev_cfn": None,
|
||||
"ts_domain": ""}
|
||||
restart_flag = threading.Event()
|
||||
sensor_dirty = threading.Event()
|
||||
intrinsics = {}
|
||||
@@ -67,11 +71,14 @@ def start_recording(duration, save_depth, out_dir=""):
|
||||
(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,
|
||||
rec.update(dir=d, t0=time.time(), save_depth=save_depth,
|
||||
color_ts=[], depth_ts=[], color_fn=[], depth_fn=[],
|
||||
arrival_ns=[], prev_cts=None, prev_cfn=None,
|
||||
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)
|
||||
st.update(on=True, frames=0, elapsed=0.0, duration=duration,
|
||||
drops=0, backjumps=0)
|
||||
print(f"[record] start -> {d} (duration={duration}s, depth={save_depth})",
|
||||
flush=True)
|
||||
return None
|
||||
@@ -89,7 +96,19 @@ def stop_recording():
|
||||
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"])
|
||||
# 时间来源说明:global_time 已禁用,时间戳来自相机硬件时钟
|
||||
# (单调,不受主机 NTP/对时算法影响,可用于速度/加速度计算)
|
||||
time_source="device hardware clock, global_time disabled",
|
||||
timestamp_domain=rec["ts_domain"],
|
||||
timestamps_ms=rec["color_ts"], # 兼容旧字段名=彩色流
|
||||
depth_timestamps_ms=rec["depth_ts"],
|
||||
color_frame_numbers=rec["color_fn"],
|
||||
depth_frame_numbers=rec["depth_fn"],
|
||||
host_arrival_monotonic_ns=rec["arrival_ns"],
|
||||
dropped_frames=st["drops"],
|
||||
timestamp_backjumps=st["backjumps"],
|
||||
sync_note="每行数据来自同一 frameset;D405 彩色取自左成像器,"
|
||||
"与深度同一次曝光,硬件级同步")
|
||||
(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)
|
||||
@@ -130,6 +149,11 @@ def capture_loop():
|
||||
align = rs.align(rs.stream.color)
|
||||
scale = profile.get_device().first_depth_sensor().get_depth_scale()
|
||||
dev = profile.get_device()
|
||||
# 禁用 global_time:librealsense 的软件对时算法会造成时间戳回跳
|
||||
# (典型 ~150ms),禁用后走相机硬件时钟,严格单调
|
||||
for s in dev.query_sensors():
|
||||
if s.supports(rs.option.global_time_enabled):
|
||||
s.set_option(rs.option.global_time_enabled, 0)
|
||||
apply_sensor_options(profile)
|
||||
frames = align.process(pipe.wait_for_frames())
|
||||
intr = frames.get_color_frame().profile.as_video_stream_profile().intrinsics
|
||||
@@ -167,7 +191,20 @@ def capture_loop():
|
||||
if rec["save_depth"]:
|
||||
cv2.imwrite(str(rec["dir"] / "depth" /
|
||||
f"{st['frames']:06d}.png"), depth_raw)
|
||||
rec["timestamps"].append(cf.get_timestamp())
|
||||
cts, dts = cf.get_timestamp(), df.get_timestamp()
|
||||
cfn, dfn = cf.get_frame_number(), df.get_frame_number()
|
||||
if not rec["ts_domain"]:
|
||||
rec["ts_domain"] = str(cf.get_frame_timestamp_domain())
|
||||
if rec["prev_cts"] is not None and cts <= rec["prev_cts"]:
|
||||
st["backjumps"] += 1
|
||||
if rec["prev_cfn"] is not None and cfn > rec["prev_cfn"] + 1:
|
||||
st["drops"] += int(cfn - rec["prev_cfn"] - 1)
|
||||
rec["prev_cts"], rec["prev_cfn"] = cts, cfn
|
||||
rec["color_ts"].append(cts)
|
||||
rec["depth_ts"].append(dts)
|
||||
rec["color_fn"].append(int(cfn))
|
||||
rec["depth_fn"].append(int(dfn))
|
||||
rec["arrival_ns"].append(time.monotonic_ns())
|
||||
st["frames"] += 1
|
||||
st["elapsed"] = time.time() - rec["t0"]
|
||||
if st["duration"] > 0 and st["elapsed"] >= st["duration"]:
|
||||
@@ -180,10 +217,15 @@ def capture_loop():
|
||||
n_win += 1
|
||||
now = time.time()
|
||||
if now - t_win >= 1.0:
|
||||
hh, ww = depth_raw.shape
|
||||
roi = depth_raw[hh // 3:2 * hh // 3, ww // 3:2 * ww // 3]
|
||||
nz = roi[roi > 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
|
||||
st["dist_cm"] = float(np.median(nz)) * scale * 100 \
|
||||
if nz.size else 0.0
|
||||
n_win, t_win = 0, now
|
||||
|
||||
# 预览合成
|
||||
@@ -295,7 +337,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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),前端拉帧循环靠它对齐相机节奏
|
||||
|
||||
+33
-2
@@ -21,7 +21,11 @@ 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)}
|
||||
#overlay{display:flex;gap:16px;margin-top:6px;font-size:13px;color:var(--dim);flex-wrap:wrap}
|
||||
#overlay .ok{color:#4cc38a}
|
||||
#overlay .warn{color:#e8a33d}
|
||||
#overlay .bad{color:var(--rec);font-weight:600}
|
||||
.hint.warn{color:#e8a33d}
|
||||
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}
|
||||
@@ -59,6 +63,7 @@ button{border:0;border-radius:8px;padding:10px 0;width:100%;font-size:16px;
|
||||
<img id="view" alt="live">
|
||||
<div id="overlay">
|
||||
<span id="ov_mode">—</span><span id="ov_fps">—</span><span id="ov_depth">—</span>
|
||||
<span id="ov_dist">—</span><span id="ov_health"></span>
|
||||
</div>
|
||||
</div>
|
||||
<aside>
|
||||
@@ -103,6 +108,7 @@ button{border:0;border-radius:8px;padding:10px 0;width:100%;font-size:16px;
|
||||
</select>
|
||||
</div>
|
||||
<div class="hint">1280×720 最高 30fps;60/90fps 需 848×480 及以下</div>
|
||||
<div class="hint" id="res_hint"></div>
|
||||
<button id="applybtn" onclick="applyStream()">应用视频流设置</button>
|
||||
</div>
|
||||
<div class="card">
|
||||
@@ -152,7 +158,7 @@ button{border:0;border-radius:8px;padding:10px 0;width:100%;font-size:16px;
|
||||
</main>
|
||||
<script>
|
||||
const $ = id => document.getElementById(id);
|
||||
let st = {on:false}, streamDirty = false;
|
||||
let st = {on:false}, streamDirty = false, synced = false;
|
||||
|
||||
// ---- 自愈式拉帧预览:/frame.jpg 服务端等新帧才返回,断了自动重连 ----
|
||||
const sleep = ms => new Promise(r=>setTimeout(r,ms));
|
||||
@@ -204,7 +210,15 @@ $('auto_exp').onchange=()=>{
|
||||
};
|
||||
|
||||
// ---- 视频流设置(需重启)----
|
||||
// 低分辨率提醒:手腕/手掌定位够用,指尖、指缝、遮挡边界需要更高分辨率
|
||||
function resHint(){
|
||||
const w=+$('res').value.split('x')[0];
|
||||
const h=$('res_hint');
|
||||
h.textContent = w<848 ? '⚠ 低于 848×480:手腕/手掌整体定位可用,指尖、指缝和遮挡边界易出错' : '';
|
||||
h.className = w<848 ? 'hint warn' : 'hint';
|
||||
}
|
||||
$('res').onchange=$('fps').onchange=()=>{
|
||||
resHint();
|
||||
streamDirty=true;
|
||||
$('applybtn').classList.add('dirty');
|
||||
$('applybtn').textContent='应用视频流设置(未生效)';
|
||||
@@ -258,6 +272,23 @@ async function poll(){
|
||||
$('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(!synced && !streamDirty){ // 首次连上:下拉框跟服务端实际配置对齐
|
||||
$('res').value=`${st.width}x${st.height}`; $('fps').value=String(st.fps);
|
||||
resHint(); synced=true;
|
||||
}
|
||||
// 工作距离:画面中心 1/3 区域深度中位数;D405 官方最佳 7–50cm
|
||||
const od=$('ov_dist'), d=st.dist_cm||0;
|
||||
if(!d){ od.textContent='中心距离 —'; od.className=''; }
|
||||
else if(d<7){ od.textContent=`中心距离 ${d.toFixed(0)}cm ⚠ 太近(<7cm)`; od.className='bad'; }
|
||||
else if(d>50){ od.textContent=`中心距离 ${d.toFixed(0)}cm ⚠ 太远(>50cm)`; od.className='bad'; }
|
||||
else { od.textContent=`中心距离 ${d.toFixed(0)}cm ✓ 7–50cm`; od.className='ok'; }
|
||||
// 时间戳健康度:录制中实时;停止后保留上一段的统计
|
||||
const oh=$('ov_health');
|
||||
if(st.on || st.frames>0){
|
||||
const bad=(st.drops>0)||(st.backjumps>0);
|
||||
oh.textContent=`${st.on?'':'上段 '}丢帧 ${st.drops} · 时间戳回跳 ${st.backjumps}`+(bad?' ⚠':' ✓');
|
||||
oh.className=bad?'bad':'ok';
|
||||
}else{ oh.textContent=''; oh.className=''; }
|
||||
if(st.error) $('msg').textContent=st.error;
|
||||
}
|
||||
setInterval(poll,1000); poll();
|
||||
|
||||
Reference in New Issue
Block a user