from pyb import Pin
import sensor, image, time
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(False) # must be turned off for color tracking
sensor.set_auto_whitebal(False) # must be turned off for color tracking
clock = time.clock()
flag=0
while(True):
clock.tick()
img = sensor.snapshot().lens_corr(1.8)
for c in img.find_circles(threshold = 3500, x_margin = 10, y_margin = 10, r_margin = 10,
r_min = 2, r_max = 100, r_step = 2):
area = (c.x()-c.r(), c.y()-c.r(), 2*c.r(), 2*c.r())#area为识别到的圆的区域,即圆的外接矩形框
statistics = img.get_statistics(roi=area)#像素颜色统计
print(statistics)
#(0,100,0,120,0,120)是红色的阈值,所以当区域内的众数(也就是最多的颜色),范围在这个阈值内,就说明是红色的圆。
#l_mode(),a_mode(),b_mode()是L通道,A通道,B通道的众数。
if 0<statistics.l_mode()<100 and 0<statistics.a_mode()<127 and 0<statistics.b_mode()<127: #if the circle is red
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))#识别到的红色圆形用红色的圆框出来
flag=1
if 0<statistics.l_mode()<100 and -40<statistics.a_mode()<30 and 0<statistics.b_mode()<50:#if the circle is green
img.draw_circle(c.x(), c.y(), c.r(), color = (0, 255, 0))#识别到的绿色圆形用绿色的圆框出来
time.sleep(1) # 延时 1 毫秒
if 0<statistics.l_mode()<100 and 0<statistics.a_mode()<127 and 0<statistics.b_mode()<127: #if the circle is red
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))#识别到的红色圆 形用红色的圆框出来
flag=2
else:
flag=3
if 0<statistics.l_mode()<100 and -40<statistics.a_mode()<0 and -40<statistics.b_mode()<20:#if the circle is blue
img.draw_circle(c.x(), c.y(), c.r(), color = (0, 0, 255))#识别到的蓝色圆形用蓝色的圆框出来
time.sleep(1) # 延时 1 毫秒
if 0<statistics.l_mode()<100 and 0<statistics.a_mode()<127 and 0<statistics.b_mode()<127: #if the circle is red
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))#识别到的红色圆形用红色的圆框出来
flag=2
else:
flag=3
while(flag):
if flag==1:
p_out = Pin('P0', Pin.OUT_PP)#设置p_out为输入引脚
p_out.high()#设置p0引脚为高
elif flag==2:
p_out = Pin('P1', Pin.OUT_PP)#设置p_out为输入引脚
p_out.high()#设置p0引脚为高
elif flag==3:
p_out = Pin('P2', Pin.OUT_PP)#设置p_out为输入引脚
p_out.high()#设置p0引脚为高
else:
print("default")
print("FPS %f" % clock.fps())你里面有一个死循环,45行。