import sensor, image, time
from pyb import UART
import json
black_threshold = (0, 20, -18, 127, -8, 22) #black
green_threshold = (0, 70, -128, -28, 22, 127) #green
red_threshold = (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()
while(True):
clock.tick()
img = sensor.snapshot()
#识别形状颜色
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):
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))
output_str="[%d,%d,%d]" % (c.x(),c.y(),c.r())
print("形状:圆形",output_str)
uart.write(output_str+'\r\n')
statistics=img.get_statistics(roi = (c.r(), c.r(), 2 * c.r(), 2 * c.r()))
blobs = img.find_blobs([red_threshold,green_threshold,black_threshold],roi=(c.r(), c.r(), 2 * c.r(), 2 * c.r()))
if blobs:
max_blob = find_max(blobs)
img.draw_rectangle(max_blob[0:4]) # rect
img.draw_cross(max_blob[5], max_blob[6]) # cx, cy
else:
pass
for r in img.find_rects(threshold = 10000):
img.draw_rectangle(r.rect(), color = (255, 0, 0))
output_str="[%d,%d,%d,%d]" % (r.x(),r.y(),r.w(),r.h())
print("形状:矩形",output_str)
uart.write(output_str+'\r\n')
area = r.rect()
blobs = img.find_blobs([red_threshold,green_threshold,black_threshold],roi=area)
if blobs:
max_blob = find_max(blobs)
img.draw_rectangle(max_blob[0:4]) # rect
img.draw_cross(max_blob[5], max_blob[6]) # cx, cy
else:
pass把所有的draw_rectangle删除,否则会影响后面的查找矩形。