Skip to content

Commit e09a62a

Browse files
Create apriltag.py
0 parents  commit e09a62a

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

apriltag.py

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import cv2
2+
import numpy
3+
from pupil_apriltags import Detector
4+
import sys
5+
6+
LINE_WIDTH = 5
7+
8+
RED = (255, 0, 0)
9+
GREEN = (0, 255, 0)
10+
BLUE = (0, 0, 255)
11+
PURPLE = (214, 48, 255)
12+
LIGHT_BLUE = (0, 255, 255)
13+
ORANGE = (255, 166, 0)
14+
15+
COLORS = [GREEN, RED, BLUE, PURPLE, LIGHT_BLUE, ORANGE]
16+
17+
def get_color(tag_id):
18+
num = tag_id % len(COLORS)
19+
return COLORS[num]
20+
21+
def convert_tag_corners(corners):
22+
new_corners = []
23+
for corner in corners:
24+
new_corner = []
25+
for cord in corner:
26+
new_corner.append(int(cord.round()))
27+
#print(cord)
28+
#print(int(cord.round()))
29+
new_corners.append(new_corner)
30+
#print(new_corner)
31+
#print(new_corners)
32+
return new_corners
33+
34+
if len(sys.argv) > 2:
35+
print("Enabled Pose")
36+
enablePose = True
37+
tagSize = int(sys.argv[2]) / 100
38+
else:
39+
enablePose = False
40+
tagSize = 0.1
41+
42+
at_detector = Detector(families='tag36h11', nthreads=1, quad_decimate=1.0, quad_sigma=0.0, refine_edges=1, decode_sharpening=0.25, debug=0)
43+
44+
cam_id = 0
45+
while True:
46+
print("Opening camera " + str(cam_id))
47+
cam = cv2.VideoCapture(cam_id)
48+
if input("Is this camera correct? (y/n): ") == "y":
49+
break
50+
cam.release()
51+
cam_id += 1
52+
53+
try:
54+
while True:
55+
_, frame = cam.read()
56+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
57+
58+
tags = at_detector.detect(gray, estimate_tag_pose=enablePose, camera_params=[1, 1, 0, 0], tag_size=tagSize)
59+
60+
height = frame.shape[0]
61+
62+
for tag in tags:
63+
color = get_color(tag.tag_id)
64+
centerpos = (int(tag.center[0]), int(tag.center[1]))
65+
centerx = centerpos[0]
66+
corners = convert_tag_corners(tag.corners)
67+
highest_corner = 0
68+
lowest_corner = height
69+
for corner in corners:
70+
y = corner[1]
71+
if y > highest_corner:
72+
highest_corner = y
73+
if y < lowest_corner:
74+
lowest_corner = y
75+
print("Rotation: ", end="")
76+
print(tag.pose_R)
77+
print("Translation: ", end="")
78+
print(tag.pose_t)
79+
80+
cv2.circle(frame, centerpos, LINE_WIDTH, color, -1)
81+
82+
cv2.line(frame, corners[0], corners[1], color, LINE_WIDTH)
83+
cv2.line(frame, corners[1], corners[2], color, LINE_WIDTH)
84+
cv2.line(frame, corners[2], corners[3], color, LINE_WIDTH)
85+
cv2.line(frame, corners[3], corners[0], color, LINE_WIDTH)
86+
87+
cv2.putText(frame, str(tag.tag_id), (centerx, (lowest_corner - 15) if lowest_corner > 0 else (highest_corner + 15)), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2, cv2.LINE_AA)
88+
cv2.imshow("apriltag", frame)
89+
keycode = cv2.waitKey(1)
90+
if keycode == 32:
91+
break
92+
finally:
93+
cam.release()
94+
cv2.destroyAllWindows()

0 commit comments

Comments
 (0)