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_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
aruco_params.maxMarkerPerimeterRate = 10.0
aruco_params.polygonalApproxAccuracyRate = 0.1
aruco_params.minCornerDistanceRate = 0.05
aruco_params.minDistanceToBorder = 0
detector = cv2.aruco.ArucoDetector(dictionary, aruco_params)
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}")
if ids is not None:
print(f"Detected Aruco markers: {ids}")
cv2.aruco.drawDetectedMarkers(image, corners, ids)
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)
cv2.polylines(image, [np.int32(c)], True, (0, 255, 0), 2)
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)
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)
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)
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)
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.结果