EndeavourDD's picture
bottle v2: correct camera-offset numbers; alignment tool reports rotation without shear
b3b8493 verified
Raw History Blame Contribute Delete
6.15 kB
"""align_camera.py — 把相机对回录数据时的位置。
实时画面(按部署时的做法:RealSense 彩色图转 RGB,整张缩到 256x256)和训练首帧
scene_reference/start_frame_raw_256.png 叠在一起显示,并在终端里每秒打印还差多少:
平移(256 图上的像素)、旋转(度)、缩放。边调相机边看,直到平移 < 1 像素、旋转 < 0.3 度、缩放在 0.99–1.01 之间。
用法(在部署包目录里运行,和 run_robot.py 放在同一层,需要能 import 仓库里的 ur5e_control):
python align_camera.py # 先把机械臂停在 START_Q、夹爪开到 0.07 m,再运行
python align_camera.py --home # 先让机械臂回 START_Q、夹爪开到 0.07 m(需要 ZMQ 机器人服务器在跑)
python align_camera.py --video x.mp4 # 不接相机,拿录好的视频测试本工具
窗口:左 = 实时画面与训练首帧各一半叠加;右 = 边缘重叠(红 = 训练首帧,青 = 实时画面,白 = 重合)。按 q 退出。
对齐顺序:先只看墙角、桌边和机械臂(它们不会动),把相机调到对齐;再把瓶子、垫子等物体摆到和训练首帧重合的位置。
"""
from __future__ import annotations
import argparse
import sys
import time
from pathlib import Path
import cv2
import numpy as np
THIS_DIR = Path(__file__).resolve().parent
START_Q = np.array([0.91772954, 0.21037714, -0.27950428, -1.91012711, 0.12014166, 2.05900554, -1.74129379])
START_GRIPPER = 0.070
def estimate(ref_gray: np.ndarray, live_gray: np.ndarray):
"""ECC 仿射配准:返回 (dx, dy, 旋转角度, 缩放);dx/dy 是 256 图上的像素,正值 = 实时画面相对训练首帧往右 / 往下偏。"""
warp = np.eye(2, 3, dtype=np.float32)
mask = np.ones(ref_gray.shape, np.uint8)
mask[:30, :120] = 0
try:
_, warp = cv2.findTransformECC(ref_gray, live_gray, warp, cv2.MOTION_AFFINE,
(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 300, 1e-6), mask, 5)
except cv2.error:
return None
a = warp[:, :2]
scale = float(np.sqrt(abs(np.linalg.det(a))))
# 取最接近的「旋转 + 等比缩放」的旋转角,不把剪切算进旋转
rot = float(np.degrees(np.arctan2(a[1, 0] - a[0, 1], a[0, 0] + a[1, 1])))
# 平移换成绕图像中心:中心点被映射到哪,减去中心
c = np.array([ref_gray.shape[1] / 2.0, ref_gray.shape[0] / 2.0])
d = a @ c + warp[:, 2] - c
return float(d[0]), float(d[1]), rot, scale
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--ref", default=str(THIS_DIR / "scene_reference" / "start_frame_raw_256.png"))
ap.add_argument("--video", default=None, help="用录好的视频代替相机(测试用)")
ap.add_argument("--home", action="store_true", help="先让机械臂回 START_Q、夹爪开到 0.07 m")
ap.add_argument("--zmq-host", default="localhost")
ap.add_argument("--zmq-port", type=int, default=5555)
ap.add_argument("--no-window", action="store_true", help="不开窗口,只在终端打印(没有显示器时用)")
args = ap.parse_args()
ref = cv2.cvtColor(cv2.imread(args.ref), cv2.COLOR_BGR2RGB)
ref_gray = cv2.cvtColor(ref, cv2.COLOR_RGB2GRAY).astype(np.float32)
ref_edge = cv2.Canny(ref, 60, 150) > 0
if args.home:
sys.path.insert(0, str(THIS_DIR.parent))
from frankar3_control.robot_communicator import RobotCommunicator
robot = RobotCommunicator(zmq_host=args.zmq_host, zmq_port=args.zmq_port)
robot.open_gripper(width=START_GRIPPER)
robot.move_to_joints(START_Q, speed_factor=0.2)
print("机械臂已回 START_Q,夹爪宽度", robot.get_gripper_width())
if args.video:
cap = cv2.VideoCapture(args.video)
def grab():
ok, bgr = cap.read()
return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) if ok else None
else:
sys.path.insert(0, str(THIS_DIR.parent))
from ur5e_control.realsense_camera_utils import (create_align_object, get_latest_images_from_realsense,
start_realsense_pipeline)
pipe = start_realsense_pipeline(agentview=True)
align = create_align_object()
def grab(): # 和 run_robot.py 的 get_base_camera_image 完全一样
bgr, _, _ = get_latest_images_from_realsense(pipe, require_depth=False, align=align)
return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
last = 0.0
while True:
rgb = grab()
if rgb is None:
break
live = cv2.resize(rgb, (256, 256))
if time.time() - last > 1.0 or args.video:
r = estimate(ref_gray, cv2.cvtColor(live, cv2.COLOR_RGB2GRAY).astype(np.float32))
if r is None:
print("配准没收敛:画面差太多,先手动把相机大致对上")
else:
dx, dy, rot, sc = r
ok = abs(dx) < 1 and abs(dy) < 1 and abs(rot) < 0.3 and abs(sc - 1) < 0.01
print(f"平移 dx={dx:+5.1f} dy={dy:+5.1f} 像素 旋转 {rot:+5.2f} 度 缩放 x{sc:.3f} {'已对齐' if ok else '还没对齐'}", flush=True)
last = time.time()
if args.video:
break # 测试模式只看第一帧
if not args.no_window:
blend = (0.5 * live + 0.5 * ref).astype(np.uint8)
over = np.zeros_like(live)
e = cv2.Canny(live, 60, 150) > 0
over[ref_edge] = (255, 60, 60)
over[e] = (60, 230, 230)
over[ref_edge & e] = (255, 255, 255)
show = cv2.resize(np.concatenate([blend, over], axis=1), (1024, 512), interpolation=cv2.INTER_NEAREST)
cv2.imshow("align_camera: left = blend, right = edges (red = train, cyan = live)", cv2.cvtColor(show, cv2.COLOR_RGB2BGR))
if cv2.waitKey(30) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()
if __name__ == "__main__":
main()