import sensor, image, time, math
import time
from pyb import Pin, Timer
# 50kHz pin6 timer2 channel1
light = Timer(2, freq=50000).channel(1, Timer.PWM, pin=Pin("P6"))
light.pulse_width_percent(100) # 控制扩展LED的亮度 0~100
thresholds = [(41, 82, -18, 11, -20, 11)]#这里填不要查找的颜色,也就是要查找除了这个颜色外的其他颜色
area=(54,21,156,201) #控制查找的区域
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(True) # must be turned off for color tracking
sensor.set_auto_whitebal(True) # must be turned off for color tracking
clock = time.clock()
while(True):
clock.tick()
img = sensor.snapshot()
for blob in img.find_blobs([thresholds[threshold_index]],roi=area,invert=True,pixels_threshold=200, area_threshold=200, merge=True):
#这里面最重要的操作: invert=True 反转阈值操作,像素在已知颜色范围之外进行匹配,而非在已知颜色范围内。
#以及roi=area 感兴趣区域的矩形元组(x,y,w,h)。如果未指定,ROI即整个图像的图像矩形。 操作范围仅限于 roi 区域内的像素。
#如果回归后的边界框区域小于 area_threshold ,则返回None。如果回归后的像素数小于 pixel_threshold ,则返回None。
#if blob.compactness()>0.5 :
img.draw_edges(blob.min_corners(), color=(255,0,0))
img.draw_line(blob.major_axis_line(), color=(0,255,0))
img.draw_line(blob.minor_axis_line(), color=(0,0,255))
print(blob.cx(),blob.cy())
img.draw_string(240, 0, "FPS:%.2f"%(clock.fps()))
img.draw_string(0,0,"%d %d" % (blob.cx(),blob.cy()))
代码运行效果: