# 导入文件
import sensor, image, time, pyb
from pyb import UART,Pin,Timer
import json
# 初始化摄像头
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()
tim = Timer(4, freq=1000) # Frequency in Hz
led_dac = tim.channel(1, Timer.PWM, pin=Pin("P7"), pulse_width_percent=50)
led_dac.pulse_width_percent(100)
# 定义颜色阈值
red_threshold = (33, 100, 17, 127, -25, 52) # 红色阈值
green_threshold = (54, 20, -47, -18, -15, 41) # 绿色阈值
yellow_threshold = (40, 100, -56, 81, 25, 127) # 黄色阈值
# 初始化串口
uart = pyb.UART(3, 115200) # 使用UART3,波特率115200
# 定义帧头和帧尾
FRAME_HEADER = 0xAA
FRAME_TAIL = 0x55
# 上一次发送的颜色
last_detected_color = None
def find_max_blob(blobs):
max_blob = None
max_size = 0
for blob in blobs:
if blob.pixels() > max_size:
max_size = blob.pixels()
max_blob = blob
return max_blob
while(True):
clock.tick() # 更新FPS帧率时钟
img = sensor.snapshot()
# 查找色块
red_blobs = img.find_blobs([red_threshold], pixels_threshold=100, area_threshold=100)
green_blobs = img.find_blobs([green_threshold], pixels_threshold=100, area_threshold=100)
yellow_blobs = img.find_blobs([yellow_threshold], pixels_threshold=100, area_threshold=100)
red_blob = find_max_blob(red_blobs)
green_blob = find_max_blob(green_blobs)
yellow_blob = find_max_blob(yellow_blobs)
if red_blob:
detected_color = "R"
elif green_blob:
detected_color = "G"
elif yellow_blob:
detected_color = "Y"
else:
detected_color = "N" # 没有识别到颜色
# 绘制矩形框和文字标注
if detected_color == "R":
img.draw_rectangle(red_blob.rect(), color=(255, 0, 0)) # 用红色矩形框圈出红色物块
img.draw_cross(red_blob.cx(), red_blob.cy(),color=(255, 0, 0), size=10)
img.draw_string(red_blob.x(), red_blob.y() - 10, "Red", color=(255, 0, 0)) # 显示文字
elif detected_color == "G":
img.draw_rectangle(green_blob.rect(), color=(0, 255, 0)) # 用绿色矩形框圈出绿色物块
img.draw_cross(green_blob.cx(), green_blob.cy(),color=(0, 255, 0), size=10)
img.draw_string(green_blob.x(), green_blob.y() - 10, "Green", color=(0, 255, 0)) # 显示文字
elif detected_color == "Y":
img.draw_rectangle(yellow_blob.rect(), color=(255, 255, 0)) # 用黄色矩形框圈出黄色物块
img.draw_cross(yellow_blob.cx(), yellow_blob.cy(),color=(255, 255, 0), size=10)
img.draw_string(yellow_blob.x(), yellow_blob.y() - 10, "Yellow", color=(255, 255, 0)) # 显示文字
# 发送颜色指令到STM32,如果识别到颜色且与上一次不同,发送带帧头和帧尾的颜色指令到STM32
if detected_color is not None and detected_color != last_detected_color:
uart.writechar(FRAME_HEADER) # 发送帧头
uart.write(detected_color) # 发送颜色指令
uart.writechar(FRAME_TAIL) # 发送帧尾
last_detected_color = detected_color # 更新上一次发送的颜色
time.sleep_ms(10) # 延时100ms
print("FPS %f" % clock.fps()) # 打印帧率
10-17
1438

05-08
1万+

12-04
328

10-03
1万+

03-28