You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求基于Python的ArUco标记移动追踪代码及获取途径

ArUco标记移动追踪Python实现

首先确保安装依赖:

pip install opencv-python opencv-contrib-python numpy

以下是完整的移动追踪代码,基于OpenCV的ArUco模块实现:

import cv2
import cv2.aruco as aruco
import numpy as np

# 替换为你的相机标定参数(需提前完成相机标定)
camera_matrix = np.array([[1000, 0, 320],
                          [0, 1000, 240],
                          [0, 0, 1]], dtype=np.float32)
dist_coeffs = np.zeros((4, 1), dtype=np.float32)  # 畸变系数,若无畸变可设为0

# 选择ArUco字典(需与你的标记字典一致)
aruco_dict = aruco.getPredefinedDictionary(aruco.DICT_6X6_250)
parameters = aruco.DetectorParameters()

# 初始化视频捕获(0为默认摄像头,也可替换为视频文件路径)
cap = cv2.VideoCapture(0)

# 存储初始位置(用于计算相对移动)
initial_translation = None

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    # 灰度转换
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 检测ArUco标记
    corners, ids, rejected = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)

    if ids is not None:
        # 估计标记的姿态(旋转向量rvec,平移向量tvec)
        rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners, 0.05, camera_matrix, dist_coeffs)
        # 0.05是标记的实际尺寸(单位:米,需替换为你的标记实际大小)

        # 遍历检测到的标记
        for i in range(len(ids)):
            # 绘制标记和坐标轴
            aruco.drawDetectedMarkers(frame, corners)
            cv2.drawFrameAxes(frame, camera_matrix, dist_coeffs, rvec[i], tvec[i], 0.03)

            # 获取当前平移向量(x,y,z方向的位置,单位:米)
            current_t = tvec[i][0]
            # 记录初始位置
            if initial_translation is None:
                initial_translation = current_t.copy()

            # 计算相对初始位置的移动量
            relative_move = current_t - initial_translation

            # 在帧上显示位置信息
            text = f"当前位置: X={current_t[0]:.3f}m Y={current_t[1]:.3f}m Z={current_t[2]:.3f}m"
            text_rel = f"相对移动: X={relative_move[0]:.3f}m Y={relative_move[1]:.3f}m Z={relative_move[2]:.3f}m"
            cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
            cv2.putText(frame, text_rel, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

    # 显示结果帧
    cv2.imshow('ArUco Movement Tracking', frame)

    # 按下q键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()

关键说明:

  • 相机标定参数:必须使用你自己相机的实际内参和畸变系数,否则平移向量的数值会不准确。可以通过OpenCV的相机标定程序获取这些参数。
  • 标记尺寸:代码中的0.05是标记的实际边长(单位米),需要替换为你打印的ArUco标记的真实尺寸。
  • 相对移动计算:通过记录初始位置,后续每一帧的平移向量减去初始值,即可得到标记的相对移动量,实现移动追踪。
  • 姿态估计:aruco.estimatePoseSingleMarkers方法同时返回旋转向量(用于方向追踪)和平移向量(用于位置/移动追踪),正好满足你的需求。

内容的提问来源于stack exchange,提问作者David Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:07:50