代码1:
import sensor, image, time
from pyb import UART
from pyb import LED
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_windowing((200, 200))
sensor.set_hmirror(True)
sensor.set_vflip(True)
sensor.skip_frames(30)
sensor.set_auto_gain(False, gain_db=13)
sensor.set_auto_whitebal(False)
uart = UART(3, 115200, timeout_char=1000)
uart.init(115200, bits=8, parity=None, stop=1)
clock = time.clock()
led_R = LED(1)
led_G = LED(2)
threshold = (97, 100, -5, 8, -5, 8)
while(True):
clock.tick()
img = sensor.snapshot()
img.binary([threshold])
circles = img.find_circles(threshold = 5000, x_margin = 10, y_margin = 10, r_margin = 10,
r_min = 3, r_max = 50, r_step = 1)
img = sensor.snapshot()
for c in circles:
area = (c.x()-c.r(), c.y()-c.r(), 2*c.r(), 2*c.r())
print(c)
statistics = img.get_statistics(roi=area)
rgb_c_l = img.get_pixel(c.x()-c.r()-8, c.y())
rgb_c_r = img.get_pixel(c.x()+c.r()+8, c.y())
rgb_c_u = img.get_pixel(c.x(), c.y()-c.r()-8)
rgb_c_d = img.get_pixel(c.x(), c.y()+c.r()+8)
if rgb_c_l==None or rgb_c_r==None or rgb_c_u==None or rgb_c_d==None:
continue
rgb_c = [0, 0, 0]
rgb_c[0] = (rgb_c_l[0] + rgb_c_r[0] + rgb_c_u[0] + rgb_c_d[0]) // 4
rgb_c[1] = (rgb_c_l[1] + rgb_c_r[1] + rgb_c_u[1] + rgb_c_d[1]) // 4
rgb_c[2] = (rgb_c_l[2] + rgb_c_r[2] + rgb_c_u[2] + AAAAAAAAAAAAAA[2]) // 4
print(rgb_c)
if 220<=rgb_c[0] and rgb_c[1]+50<rgb_c[0] and rgb_c[2]+50<rgb_c[0]:
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))
print('traffic light is red')
uart.write('traffic light is red')
led_R.on()
elif rgb_c[0]+80<rgb_c[1] and 220<=rgb_c[1] and rgb_c[2]+50<rgb_c[1]:
img.draw_circle(c.x(), c.y(), c.r(), color = (0, 255, 0))
print('traffic light is green')
uart.write('traffic light is green')
led_G.on()
elif 220<=rgb_c[0] and rgb_c[1]+80<=rgb_c[0] and rgb_c[2]+150<rgb_c[0]:
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 255, 0))
print('traffic light is yellow')
uart.write('traffic light is yellow')
else:
led_R.off()
led_G.off()
代码二
import sensor, image
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA) # can be QVGA on M7...
sensor.skip_frames(30)
sensor.set_auto_gain(False) # must turn this off to prevent image washout...
while(True):
img = sensor.snapshot()
img.lens_corr(1.8) # strength of 1.8 is good for the 2.8mm lens.
for code in img.find_qrcodes():
print(code)
结果: