import sensor, image, time, math
from pyb import LED
# 初始化摄像头
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()
# 定义颜色阈值 (LAB格式: L, A, B 最小值与最大值)
red_threshold = (30, 100, 15, 127, 15, 127)
green_threshold = (30, 100, -128, -15, -128, 15)
blue_threshold = (30, 100, -128, 127, -128, -15)
# 初始化LED用于状态指示
red_led = LED(1)
green_led = LED(2)
blue_led = LED(3)
while(True):
clock.tick()
img = sensor.snapshot()
# 检测二维码
for code in img.find_qrcodes():
img.draw_rectangle(code.rect(), color=(255, 0, 0))
img.draw_string(code.x(), code.y(), code.payload(), color=(0, 255, 0))
print("QR Code: ", code.payload())
red_led.on()
green_led.off()
blue_led.off()
# 检测颜色块
max_area = 0
color_flag = 0
for blob in img.find_blobs([red_threshold], pixels_threshold=100, area_threshold=100):
if blob.area() > max_area:
max_area = blob.area()
color_flag = 1
img.draw_rectangle(blob.rect(), color=(255, 0, 0))
img.draw_cross(blob.cx(), blob.cy(), color=(0, 255, 0))
for blob in img.find_blobs([green_threshold], pixels_threshold=100, area_threshold=100):
if blob.area() > max_area:
max_area = blob.area()
color_flag = 2
img.draw_rectangle(blob.rect(), color=(0, 255, 0))
img.draw_cross(blob.cx(), blob.cy(), color=(0, 255, 0))
for blob in img.find_blobs([blue_threshold], pixels_threshold=100, area_threshold=100):
if blob.area() > max_area:
max_area = blob.area()
color_flag = 3
img.draw_rectangle(blob.rect(), color=(0, 0, 255))
img.draw_cross(blob.cx(), blob.cy(), color=(0, 255, 0))
# 根据识别结果控制LED
if color_flag == 1:
red_led.on()
green_led.off()
blue_led.off()
elif color_flag == 2:
red_led.off()
green_led.on()
blue_led.off()
elif color_flag == 3:
red_led.off()
green_led.off()
blue_led.on()
else:
red_led.off()
green_led.off()
blue_led.off()