Files

91 lines
4.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""D405 实时预览窗口,帮你把棋盘格标定板摆到位(完整在画面里 + 落进甜区 + 正对)。
自动轮询常见棋盘格网格并锁定;叠加检测角点、板到相机距离、是否在 D405 甜区。
按键:s=保存当前帧(管线格式) 到 --out;q/ESC=退出。
用法:DISPLAY=:1 .venv/bin/python scripts/realsense_live.py --out data/real_calib [--cols 9 --rows 6]
"""
import argparse, json
from pathlib import Path
import numpy as np, cv2
import pyrealsense2 as rs
ROOT = Path(__file__).resolve().parents[1]
CANDIDATES = [(9, 6), (8, 6), (7, 6), (9, 7), (8, 5), (7, 5), (6, 5), (10, 7), (11, 8), (8, 4)]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="data/real_calib")
ap.add_argument("--w", type=int, default=848); ap.add_argument("--h", type=int, default=480)
ap.add_argument("--cols", type=int, default=None); ap.add_argument("--rows", type=int, default=None)
a = ap.parse_args()
grids = [(a.cols, a.rows)] if a.cols and a.rows else CANDIDATES
locked = grids[0] if (a.cols and a.rows) else None
pipe = rs.pipeline(); cfg = rs.config()
cfg.enable_stream(rs.stream.depth, a.w, a.h, rs.format.z16, 30)
cfg.enable_stream(rs.stream.color, a.w, a.h, rs.format.bgr8, 30)
profile = pipe.start(cfg)
dev = profile.get_device(); depth_scale = dev.first_depth_sensor().get_depth_scale()
align = rs.align(rs.stream.color)
intr = profile.get_stream(rs.stream.color).as_video_stream_profile().get_intrinsics()
fx, fy, cx, cy = intr.fx, intr.fy, intr.ppx, intr.ppy
win = "D405 live - move board | s=save q=quit"
cv2.namedWindow(win, cv2.WINDOW_NORMAL)
i = 0
try:
while True:
i += 1
fr = align.process(pipe.wait_for_frames())
cf, df = fr.get_color_frame(), fr.get_depth_frame()
if not cf or not df:
continue
color = np.asanyarray(cf.get_data()); depth_m = np.asanyarray(df.get_data()).astype(np.float32) * depth_scale
g = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)
gs = cv2.resize(g, None, fx=0.5, fy=0.5) # 半分辨率检测提速
found, corners, grid = False, None, locked
trylist = [locked] if locked else [grids[i % len(grids)]]
for gr in trylist:
ok, cor = cv2.findChessboardCorners(gs, gr, flags=cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_NORMALIZE_IMAGE + cv2.CALIB_CB_FAST_CHECK)
if ok:
found, corners, grid, locked = True, cor * 2.0, gr, gr
break
vis = color.copy()
if found:
cv2.drawChessboardCorners(vis, grid, corners, True)
pts = corners.reshape(-1, 2).astype(int)
us = np.clip(pts[:, 0], 0, a.w - 1); vs = np.clip(pts[:, 1], 0, a.h - 1)
dz = depth_m[vs, us]; dz = dz[dz > 0]
dist = np.median(dz) * 100 if len(dz) else 0
inr = 7 <= dist <= 50
msg = f"BOARD {grid[0]}x{grid[1]} FOUND dist={dist:.0f}cm {'[OK sweet spot]' if inr else '[move to 15-40cm]'}"
col = (80, 220, 80) if inr else (60, 180, 240)
else:
cen = depth_m[a.h // 3:2 * a.h // 3, a.w // 3:2 * a.w // 3]; cen = cen[cen > 0]
dc = np.median(cen) * 100 if len(cen) else 0
msg = f"searching board... center depth={dc:.0f}cm (keep WHOLE board in frame)"
col = (60, 160, 240)
cv2.rectangle(vis, (0, 0), (a.w, 30), (0, 0, 0), -1)
cv2.putText(vis, msg, (8, 21), cv2.FONT_HERSHEY_SIMPLEX, 0.6, col, 2, cv2.LINE_AA)
cv2.putText(vis, "s=save q=quit", (a.w - 150, a.h - 12), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (230, 230, 230), 1, cv2.LINE_AA)
cv2.imshow(win, vis)
k = cv2.waitKey(1) & 0xFF
if k in (ord('q'), 27):
break
if k == ord('s'):
out = ROOT / a.out; out.mkdir(parents=True, exist_ok=True)
depth_mm = np.clip(np.round(depth_m * 1000), 0, 65535).astype(np.uint16)
cv2.imwrite(str(out / "rgb.png"), color); cv2.imwrite(str(out / "depth.png"), depth_mm)
(out / "intrinsics.txt").write_text(f"{fx:.4f} {fy:.4f} {cx:.4f} {cy:.4f}\n")
meta = {"source": "realsense_d405", "width": a.w, "height": a.h, "K": [[fx, 0, cx], [0, fy, cy], [0, 0, 1]],
"T_world_cam_opencv": np.eye(4).tolist(), "cam_pos_world": [0, 0, 0], "depth_unit": "mm(uint16)",
"board_grid": list(grid) if found else None, "extrinsic_status": "UNCALIBRATED", "objects": {}}
(out / "camera.json").write_text(json.dumps(meta, indent=2))
print(f"[saved] {out} board={'%dx%d' % grid if found else 'not-detected'}")
finally:
pipe.stop(); cv2.destroyAllWindows()
if __name__ == "__main__":
main()