在python中有几个实现的apriltag包。在windows下:
pip install pupil-apriltags
在linux下:
pip install apriltag
这个例子中读取一个图像文件并进行检测
#!/usr/bin/env python
# coding: UTF-8
import apriltag
#import pupil_apriltags as apriltag # for windows
import cv2
import numpy as np
import sys
img =cv2.imread("apriltag_image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 创建一个apriltag检测器
at_detector = apriltag.Detector(apriltag.DetectorOptions(families='tag36h11 tag25h9') )
# at_detector = apriltag.Detector(families='tag36h11 tag25h9') #for windows
# 进行apriltag检测,得到检测到的apriltag的列表
tags = at_detector.detect(gray)
print("%d apriltags have been detected."%len(tags))
for tag in tags:
cv2.circle(img, tuple(tag.corners[0].astype(int)), 4,(255,0,0), 2) # left-top
cv2.circle(img, tuple(tag.corners[1].astype(int)), 4,(255,0,0), 2) # right-top
cv2.circle(img, tuple(tag.corners[2].astype(int)), 4,(255,0,0), 2) # right-bottom
cv2.circle(img, tuple(tag.corners[3].astype(int)), 4,(255,0,0), 2) # left-bottom
cv2.imshow("apriltag_test",img)
cv2.waitKey()
其中获得的apriltag码的四个顶点可以通过homography变换到标准apriltag码的(-1,1),(1,1),(1,-1),(-1,-1)顶点。
这个示例中,我们持续读取来自摄像头的图像,检测其中的apriltag,并进行动态的显示
#!/usr/bin/env python
# coding: UTF-8
import apriltag
#import pupil_apriltags as apriltag # for windows
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
at_detector = apriltag.Detector(apriltag.DetectorOptions(families='tag36h11 tag25h9') )
# at_detector = apriltag.Detector(families='tag36h11 tag25h9') #for windows
i=0
while(1):
# 获得图像
ret, frame = cap.read()
# 检测按键
k=cv2.waitKey(1)
if k==27:
break
elif k==ord('s'):
cv2.imwrite('E:/OpenCV_pic/'+str(i)+'.jpg', frame)
i+=1
# 检测apriltag
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
tags = at_detector.detect(gray)
for tag in tags:
cv2.circle(frame, tuple(tag.corners[0].astype(int)), 4, (255, 0, 0), 2) # left-top
cv2.circle(frame, tuple(tag.corners[1].astype(int)), 4, (255, 0, 0), 2) # right-top
cv2.circle(frame, tuple(tag.corners[2].astype(int)), 4, (255, 0, 0), 2) # right-bottom
cv2.circle(frame, tuple(tag.corners[3].astype(int)), 4, (255, 0, 0), 2) # left-bottom
# 显示检测结果
cv2.imshow('capture', frame)
cap.release()
cv2.destroyAllWindows()
当运行这个代码对tag16h5的apriltag码进行检测时,可以看到显示的图像上会有假的apriltag出现:
而对tag36h11和tag25h9码进行检测则不会出现。原因应该是tag16h5码过于简单,容错率比较低,当图像具有丰富的变化时就很容易出现误检测。所以尽量使用tag36h11和tag25h9码。