apriltag_tracking.py
import csi
import time
EXPOSURE_MICROSECONDS = 20000
SEARCHING_RESOLUTION = csi.QVGA
TRACKING_RESOLUTION = csi.QQVGA
TRACKING_LOW_RATIO_THRESHOLD = (
0.2
)
TRACKING_HIGH_RATIO_THRESHOLD = (
0.8
)
csi0 = csi.CSI()
csi0.reset()
csi0.pixformat(csi.GRAYSCALE)
csi0.framesize(SEARCHING_RESOLUTION)
csi0.snapshot(time=1000)
clock = time.clock()
csi0.auto_gain(False)
csi0.auto_exposure(False, exposure_us=EXPOSURE_MICROSECONDS)
csi0.snapshot(time=1000)
x, y, sensor_w, sensor_h = csi0.ioctl(csi.IOCTL_GET_READOUT_WINDOW)
while True:
clock.tick()
img = csi0.snapshot()
tags = img.find_apriltags()
if len(tags):
best_tag = max(tags, key=lambda x: x.decision_margin)
img.draw_rectangle(best_tag.rect)
readout_window_w = ((sensor_w // csi0.width()) * csi0.width()) / 2
readout_window_h = ((sensor_h // csi0.height()) * csi0.height()) / 2
def get_mapped_centroid(t):
x, y, w, h = csi0.ioctl(csi.IOCTL_GET_READOUT_WINDOW)
ratio = min(w / float(csi0.width()), h / float(csi0.height()))
mapped_cx = (t.cx - (csi0.width() / 2.0)) * ratio
mapped_cx += (w - (csi0.width() * ratio)) / 2.0
mapped_cx += x + (sensor_w / 2.0)
mapped_cy = (t.cy - (csi0.height() / 2.0)) * ratio
mapped_cy += (h - (csi0.height() * ratio)) / 2.0
mapped_cy += y + (sensor_h / 2.0)
return (mapped_cx, mapped_cy)
def center_on_tag(t, res):
global readout_window_w
global readout_window_h
mapped_cx, mapped_cy = get_mapped_centroid(t)
csi0.framesize(res)
x = int(mapped_cx - (sensor_w / 2.0))
y = int(mapped_cy - (sensor_h / 2.0))
w = int(readout_window_w)
h = int(readout_window_h)
csi0.ioctl(csi.IOCTL_SET_READOUT_WINDOW, (x, y, w, h))
new_x, new_y, w, h = csi0.ioctl(csi.IOCTL_GET_READOUT_WINDOW)
x_error = x - new_x
y_error = y - new_y
if x_error < 0:
print("-X Limit Reached ", end="")
if x_error > 0:
print("+X Limit Reached ", end="")
if y_error < 0:
print("-Y Limit Reached ", end="")
if y_error > 0:
print("+Y Limit Reached ", end="")
center_on_tag(best_tag, TRACKING_RESOLUTION)
loss_count = 0
while True:
clock.tick()
img = csi0.snapshot()
tags = img.find_apriltags()
if not len(tags):
if loss_count < 2:
loss_count += 1
continue
csi0.framesize(SEARCHING_RESOLUTION)
csi0.ioctl(csi.IOCTL_SET_READOUT_WINDOW, (sensor_w, sensor_h))
break
loss_count = 0
best_tag = max(tags, key=lambda x: x.decision_margin)
img.draw_rectangle(best_tag.rect)
print(clock.fps(), "TAG cx:%d, cy:%d" % get_mapped_centroid(best_tag))
w_ratio = best_tag.w / csi0.width()
h_ratio = best_tag.h / csi0.height()
while (w_ratio < TRACKING_LOW_RATIO_THRESHOLD) or (
h_ratio < TRACKING_LOW_RATIO_THRESHOLD
):
readout_window_w /= 2
readout_window_h /= 2
w_ratio *= 2
h_ratio *= 2
while (TRACKING_HIGH_RATIO_THRESHOLD < w_ratio) or (
TRACKING_HIGH_RATIO_THRESHOLD < h_ratio
):
readout_window_w *= 2
readout_window_h *= 2
w_ratio /= 2
h_ratio /= 2
center_on_tag(best_tag, TRACKING_RESOLUTION)
print(clock.fps())