工程训练题,OPEMMV 识别红黄蓝三种颜色的物块并串口返回物块坐标
话不多说,直接看代码吧
// An highlighted block
var foo = 'bar';import sensor, image, time
from pyb import UART
import json
# 颜色追踪的例子,一定要控制环境的光,保持光线是稳定的。
green_threshold = ( 50, 70, -70, -10, -20, 30)
red_threshold = ( 45, 70, 60, 80, 0, 60)
yellow_threshold = ( 65, 100, -30, 10, 20, 80)
blue_threshold = ( 45, 75, -40, 0, -50, -30)
uart = UART(3, 9600)
RX = 0
RY = 0
GX = 0
GY = 0
BX = 0
BY = 0
sensor.reset() # 初始化摄像头
sensor.set_pixformat(sensor.RGB565) # 格式为 RGB565.
sensor.set_framesize(sensor.QQVGA) # 使用 QQVGA 速度快一些
sensor.skip_frames(time = 2000) # 跳过2000s,使新设置生效,并自动调节白平衡
sensor.set_auto_gain(False) # 关闭自动自动增益。默认开启的,在颜色识别中,一定要关闭白平衡。
sensor.set_auto_whitebal(False)
#关闭白平衡。白平衡是默认开启的,在颜色识别中,一定要关闭白平衡。
clock = time.clock() # 追踪帧率
while(True):
clock.tick() # Track elapsed milliseconds between snapshots().
img = sensor.snapshot() # 从感光芯片获得一张图像
green_blobs = img.find_blobs([green_threshold],area_threshold=600)
if green_blobs:
for b in green_blobs:
img.draw_rectangle(b[0:4],color=(0,255,0))
img.draw_cross(b[5], b[6],color=(0,255,0))
GX = b.cx()
GY = b.cy()
red_blobs = img.find_blobs([red_threshold],area_threshold=600)
if red_blobs:
for b in red_blobs:
img.draw_rectangle(b[0:4],color=(255,0,0))
img.draw_cross(b[5], b[6],color=(255,0,0))
RX = b.cx()
RY = b.cy()
blue_blobs = img.find_blobs([blue_threshold],area_threshold=600)
if blue_blobs:
for b in blue_blobs:
img.draw_rectangle(b[0:4],color=(0,0,255))
img.draw_cross(b[5], b[6],color=(0,0,255))
BX = b.cx()
BY = b.cy()
print('RX:',RX,'RY:',RY ,'GX:',GX ,'GY:',GY ,'BX:',BX ,'BY:',BY )