import sensor, image, time
from pyb import UART
import json
threshold = [(0, 20, -18, 127, -8, 22), #black
(0, 70, -128, -28, 22, 127), #green
(0, 50, -128, 127, 12, 127)] #red
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()
uart = UART(3, 115200)
while(True):
clock.tick()
img = sensor.snapshot().lens_corr(1.8)
for c in img.find_circles(threshold = 3500, x_margin =2, y_margin =2, r_margin = 10,r_min = 5,r_max = 100, r_step = 2):
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))
print("圆形")
print(c)
area = (c.x() - c.r(), c.y() - c.r(), 2 * c.r(), 2 * c.r())
# area为识别到的圆的区域,即圆的外接矩形框
statistics = img.get_statistics(threshold,roi=area) # 像素颜色统计
print(statistics)
if 0<statistics.l_mode()<70 and -127<statistics.a_mode()<-25 and 20<statistics.b_mode()<127:#if the circle is red
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))#识别到的绿色圆形用红色的圆框出来
elif 0<statistics.l_mode()<30 and -18<statistics.a_mode()<127 and -8<statistics.b_mode()<22:#if the circle is red
img.draw_circle(c.x(), c.y(), c.r(), color = (0, 255, 0))#识别到的黑色圆形用红色的圆框出来
elif 0<statistics.l_mode()<50 and -128<statistics.a_mode()<127 and 12<statistics.b_mode()<127:#if the circle is red
img.draw_circle(c.x(), c.y(), c.r(), color = (0, 0, 255))#识别到的红色圆形用红色的圆框出来
else:
img.draw_rectangle(area, color = (255, 255, 255))
#将非红色的圆用白色的矩形框出来
for r in img.find_rects(threshold=15500):
img.draw_rectangle(r.rect(), color = (255, 0, 0))
area = (r[0], r[1], r[2], r[3])
statistics = img.get_statistics(threshold,roi=area) # 像素颜色统计
print(statistics)
if 0<statistics.l_mode()<70 and -127<statistics.a_mode()<-25 and 20<statistics.b_mode()<127:#if the circle is red
img.draw_rectangle(r[0], r[1], r[2], r[3], color = (255, 0, 0))#识别到的绿色圆形用红色的圆框出来
elif 0<statistics.l_mode()<30 and -18<statistics.a_mode()<127 and -8<statistics.b_mode()<22:#if the circle is red
img.draw_rectangle(r[0], r[1], r[2], r[3], color = (0, 255, 0))#识别到的黑色圆形用红色的圆框出来
elif 0<statistics.l_mode()<50 and -128<statistics.a_mode()<127 and 12<statistics.b_mode()<127:#if the circle is red
img.draw_rectangle(r[0], r[1], r[2], r[3], color = (0, 0, 255))#识别到的红色圆形用红色的圆框出来
else:
img.draw_rectangle(area, color = (255, 255, 255))
#将非红色的圆用白色的矩形框出来
print("矩形":r)
print("FPS %f" % clock.fps())
代码需要自己编写,论坛只会帮忙解决错误和问题。
https://singtown.com/learn/50029/