Example: 01-Camera/08-Readout-Control/apriltag_tracking.py
import sensor
import time
EXPOSURE_MICROSECONDS = 20000
SEARCHING_RESOLUTION = sensor.QVGA
TRACKING_RESOLUTION = sensor.QQVGA
TRACKING_LOW_RATIO_THRESHOLD = (
0.2
)
TRACKING_HIGH_RATIO_THRESHOLD = (
0.8
)
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(SEARCHING_RESOLUTION)
sensor.skip_frames(time=1000)
clock = time.clock()
sensor.set_auto_gain(False)
sensor.set_auto_exposure(False, exposure_us=EXPOSURE_MICROSECONDS)
sensor.skip_frames(time=1000)
x, y, sensor_w, sensor_h = sensor.ioctl(sensor.IOCTL_GET_READOUT_WINDOW)
while True:
clock.tick()
img = sensor.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 // sensor.width()) * sensor.width()) / 2
readout_window_h = ((sensor_h // sensor.height()) * sensor.height()) / 2
def get_mapped_centroid(t):
x, y, w, h = sensor.ioctl(sensor.IOCTL_GET_READOUT_WINDOW)
ratio = min(w / float(sensor.width()), h / float(sensor.height()))
mapped_cx = (t.cx - (sensor.width() / 2.0)) * ratio
mapped_cx += (w - (sensor.width() * ratio)) / 2.0
mapped_cx += x + (sensor_w / 2.0)
mapped_cy = (t.cy - (sensor.height() / 2.0)) * ratio
mapped_cy += (h - (sensor.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)
sensor.set_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)
sensor.ioctl(sensor.IOCTL_SET_READOUT_WINDOW, (x, y, w, h))
new_x, new_y, w, h = sensor.ioctl(sensor.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 = sensor.snapshot()
tags = img.find_apriltags()
if not len(tags):
if loss_count < 2:
loss_count += 1
continue
sensor.set_framesize(SEARCHING_RESOLUTION)
sensor.ioctl(sensor.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 / sensor.width()
h_ratio = best_tag.h / sensor.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())