【讲解+样例】使用opencv对aruco Markers识别-二、样例

时间:2024-10-04 07:48:07

1.代码

import cv2
import numpy as np

print(cv2.__version__)

# 从文件读取图像
image = cv2.imread('./markers.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 指定字典类型
dict_type = cv2.aruco.DICT_6X6_1000

# 加载预定义字典
dictionary = cv2.aruco.getPredefinedDictionary(dict_type)

# 创建Aruco参数
aruco_params = cv2.aruco.DetectorParameters()
aruco_params.adaptiveThreshWinSi* = 3  #
aruco_params.adaptiveThreshWinSizeMax = 80  #
aruco_params.adaptiveThreshWinSizeStep = 10  # 代表自适应阈值的窗口大小
aruco_params.adaptiveThreshConstant = 7  # 代表自适应阈值的常数
aruco_params.minMarkerPerimeterRate = 0.1  # 假设marker至少占图像的10%
aruco_params.maxMarkerPerimeterRate = 10.0  # 允许marker最大占图像的80%
aruco_params.polygonalApproxAccuracyRate = 0.1  # 代表多边形逼近的精度
aruco_params.minCornerDistanceRate = 0.05  # 代表marker的最小角距离
aruco_params.minDistanceToBorder = 0  # 代表marker的最小边界距离

# 创建Aruco检测器
detector = cv2.aruco.ArucoDetector(dictionary, aruco_params)

# 检测Aruco markers
corners, ids, rejected = detector.detectMarkers(gray)
print(f"Adaptive Threshold - Detected: {len(corners)}, Rejected: {len(rejected)}")

rej_img = image.copy()
for r in rejected:
    try:
        pts = r.reshape((-1, 1, 2)).astype(np.int32)
        cv2.polylines(rej_img, [pts], True, (0, 0, 255), 2)
    except Exception as e:
        print(f"Error drawing rejected candidate: {e}")

# 如果检测到markers,绘制它们
if ids is not None:
    print(f"Detected Aruco markers: {ids}")
    cv2.aruco.drawDetectedMarkers(image, corners, ids)

    # 遍历每个检测到的marker
    for i in range(len(ids)):
        c = corners[i][0]
        cv2.putText(image, f"id: {ids[i][0]}", (int(c[0][0]), int(c[0][1]) - 15),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        # 绘制marker的边界框
        cv2.polylines(image, [np.int32(c)], True, (0, 255, 0), 2)

        # 计算marker的中心
        cx = int((c[0][0] + c[2][0]) / 2)
        cy = int((c[0][1] + c[2][1]) / 2)
        cv2.circle(image, (cx, cy), 2, (0, 0, 255), -1)

        # 计算marker的方向
        cv2.line(image, (cx, cy), (int(c[0][0]), int(c[0][1])), (255, 0, 0), 2)
        cv2.line(image, (cx, cy), (int(c[1][0]), int(c[1][1])), (0, 255, 0), 2)

        # 计算marker的旋转角度
        dx = c[0][0] - c[1][0]
        dy = c[0][1] - c[1][1]
        angle = np.arctan2(dy, dx)
        angle = np.degrees(angle)
        cv2.putText(image, f"angle: {angle:.1f}", (cx, cy + 15),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        # 计算marker的尺寸
        size = np.sqrt(dx * dx + dy * dy)
        cv2.putText(image, f"size: {size:.1f}", (cx, cy + 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        # 计算marker的坐标
        cv2.putText(image, f"({cx},{cy})", (cx, cy + 45),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

# 显示结果
cv2.imshow('gray', gray)
cv2.imshow('Image with rejected candidates', rej_img)
cv2.imshow("Aruco markers", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

2.结果

在这里插入图片描述