Example: 02-Image-Processing/02-Color-Tracking/single_color_code_tracking.py
# 本作品采用MIT许可证授权。
# 版权所有 (c) 2013-2023 OpenMV LLC。保留所有权利。
# https://github.com/openmv/openmv/blob/master/LICENSE
#
# 单色代码跟踪示例
#
# 此示例展示了使用OpenMV Cam进行单色代码跟踪。
#
# 色码是由两种或以上颜色组成的色块。以下示例将仅追踪
# 仅跟踪包含以下两种颜色的彩色物体。
import sensor
import time
import math
# 颜色跟踪阈值(L 最小值,L 最大值,A 最小值,A 最大值,B 最小值,B 最大值)
# 以下阈值通常跟踪红色/绿色物体。您可能需要调整它们...
thresholds = [
(
30,
100,
15,
127,
15,
127,
), # generic_red_thresholds -> 索引为0,因此代码 == (1 << 0)
(30, 100, -64, -8, -32, 32),
] # generic_green_thresholds -> 索引为1,因此代码 == (1 << 1)
# 当“merge=True”用于“find_blobs”时,代码会进行或运算合并。
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False) # 必须关闭以进行颜色跟踪
sensor.set_auto_whitebal(False) # 必须关闭以进行颜色跟踪
clock = time.clock()
# 只有像素数超过“pixel_threshold”且面积超过“area_threshold”的blob才会被
# “find_blobs”返回。如果更改了“pixels_threshold”和“area_threshold”,请进行相应调整。
# 相机分辨率。必须设置“merge=True”以合并重叠的颜色块用于颜色代码。
while True:
clock.tick()
img = sensor.snapshot()
for blob in img.find_blobs(
thresholds, pixels_threshold=100, area_threshold=100, merge=True
):
if blob.code() == 3: # 红/绿代码 == (1 << 1) | (1 << 0)
# 这些数值依赖于色块非圆形的特性——否则它们会变得不稳定。
if blob.elongation() > 0.5:
img.draw_edges(blob.min_corners(), color=(255, 0, 0))
img.draw_line(blob.major_axis_line(), color=(0, 255, 0))
img.draw_line(blob.minor_axis_line(), color=(0, 0, 255))
# 这些数值始终保持稳定。
img.draw_rectangle(blob.rect())
img.draw_cross(blob.cx(), blob.cy())
# 注意 - 色块旋转角度仅在0-180度范围内唯一。
img.draw_keypoints(
[(blob.cx(), blob.cy(), int(math.degrees(blob.rotation())))], size=20
)
print(clock.fps())