Files

110 lines
5.4 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.
"""从真机 Intel RealSense D405 抓一帧 RGB-D,落成与仿真完全一致的管线格式,供 perceive_object.py 直接吃。
rgb.png / depth.png(uint16 mm) / intrinsics.txt(fx fy cx cy) / camera.json
外参 T_world_cam:手眼标定前先用占位值(--extrinsic 给标定结果的 4x4,逗号分隔 16 个数;不给则写单位阵并标 uncalibrated)。
读当前视角只看 rgb/depth 不需要外参;感知定位到基座系才需要标定好的外参。
自体滤除:如传 --read-joints,采集时连接 rosbridge 读取双臂关节角写进 camera.json,供 perceive_object --self-filter 用。
用法:.venv/bin/python scripts/realsense_capture.py --out data/real_cap [--w 848 --h 480] [--extrinsic "..."] [--read-joints]
"""
import argparse, json, time, sys
from pathlib import Path
import numpy as np, cv2
import pyrealsense2 as rs
ROOT = Path(__file__).resolve().parents[1]
def read_arm_joints():
"""从真机 rosbridge 读取双臂当前关节角(用于自体滤除)"""
sys.path.insert(0, str(ROOT / "scripts"))
from real_arm import RealArm
try:
arm_r = RealArm(side="right")
arm_l = RealArm(side="left")
state_r = arm_r.read(fresh=True, timeout=2.0)
state_l = arm_l.read(fresh=True, timeout=2.0)
arm_r.close()
arm_l.close()
return {
"arm_joints_right": state_r["joints"].tolist(),
"arm_joints_left": state_l["joints"].tolist(),
}
except Exception as e:
print(f"警告:读取臂关节角失败 ({e}),自体滤除将不可用")
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="data/real_cap")
ap.add_argument("--w", type=int, default=848); ap.add_argument("--h", type=int, default=480)
ap.add_argument("--warmup", type=int, default=30, help="丢弃前 N 帧等自动曝光/深度稳定")
ap.add_argument("--extrinsic", default=None, help="标定得到的 T_base_cam(OpenCV约定) 4x4,16 个数逗号分隔;不给则写单位阵(uncalibrated)")
ap.add_argument("--read-joints", action="store_true", help="采集时读取双臂关节角,写入 camera.json 供自体滤除用")
a = ap.parse_args()
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()
print("device:", dev.get_info(rs.camera_info.name), "fw", dev.get_info(rs.camera_info.firmware_version))
depth_scale = dev.first_depth_sensor().get_depth_scale() # 单位→米
align = rs.align(rs.stream.color) # 深度对齐到彩色
# 读取臂关节角(在采集相机帧之前,确保时间同步)
arm_joints = read_arm_joints() if a.read_joints else None
try:
for _ in range(a.warmup):
pipe.wait_for_frames()
frames = align.process(pipe.wait_for_frames())
cf = frames.get_color_frame(); df = frames.get_depth_frame()
assert cf and df, "没拿到彩色/深度帧"
color = np.asanyarray(cf.get_data()) # BGR
depth_raw = np.asanyarray(df.get_data()).astype(np.float32) * depth_scale # 米
depth_mm = np.clip(np.round(depth_raw * 1000.0), 0, 65535).astype(np.uint16)
intr = cf.profile.as_video_stream_profile().get_intrinsics() # 对齐后用彩色内参
fx, fy, cx, cy = intr.fx, intr.fy, intr.ppx, intr.ppy
finally:
pipe.stop()
out = ROOT / a.out; out.mkdir(parents=True, exist_ok=True)
cv2.imwrite(str(out / "rgb.png"), color) # 已是 BGR,直接存
cv2.imwrite(str(out / "depth.png"), depth_mm)
(out / "intrinsics.txt").write_text(f"{fx:.4f} {fy:.4f} {cx:.4f} {cy:.4f}\n")
if a.extrinsic:
T = np.array([float(x) for x in a.extrinsic.replace("[", "").replace("]", "").split(",")]).reshape(4, 4)
calib = "calibrated"
else:
T = np.eye(4); calib = "UNCALIBRATED(单位阵,点云=相机系;标定后用 --extrinsic 传入 T_base_cam)"
K = [[fx, 0, cx], [0, fy, cy], [0, 0, 1]]
meta = {"source": "realsense_d405", "width": a.w, "height": a.h, "K": K,
"T_world_cam_opencv": T.tolist(), "cam_pos_world": T[:3, 3].tolist(),
"depth_unit": "mm(uint16)", "depth_scale_m": depth_scale, "extrinsic_status": calib, "objects": {}}
# 添加臂关节角(如果读取成功)
if arm_joints:
meta.update(arm_joints)
# 与 perceive_object 的嵌套字段契约一致,同时保留旧的扁平字段兼容已有工具。
meta["arm_joints"] = {"right": arm_joints["arm_joints_right"],
"left": arm_joints["arm_joints_left"]}
print(f"已保存双臂关节角(用于自体滤除)")
(out / "camera.json").write_text(json.dumps(meta, indent=2))
v = depth_mm[depth_mm > 0]
hole = 100.0 * (depth_mm == 0).mean()
# 深度上色图便于肉眼看质量
dcol = cv2.applyColorMap(cv2.convertScaleAbs(depth_mm, alpha=0.03), cv2.COLORMAP_JET)
dcol[depth_mm == 0] = (0, 0, 0)
cv2.imwrite(str(out / "depth_color.png"), dcol)
print(f"wrote {out}: rgb {color.shape}, K fx={fx:.1f} cx={cx:.1f} cy={cy:.1f}")
print(f"depth(mm) min/median/max = {int(v.min())}/{int(np.median(v))}/{int(v.max())}, 空洞(无深度)占比 = {hole:.1f}%")
print(f"外参: {calib}")
if __name__ == "__main__":
main()