import sensor, image, time
from pid import PID
from pyb import Servo
from pyb import UART
import json
pan_servo=Servo(1) #下
tilt_servo=Servo(2) #上
yellow_threshold = (100, 0, -128, 53, 39, 127)
pan_pid = PID(p=0.07, i=0, imax=90) #脱机运行或者禁用图像传输,使用这个PID
tilt_pid = PID(p=0.05, i=0, imax=90) #脱机运行或者禁用图像传输,使用这个PID
#pan_pid = PID(p=0.1, i=0, imax=90)#在线调试使用这个PID
#tilt_pid = PID(p=0.1, i=0, imax=90)#在线调试使用这个PID
sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565) # use RGB565.
sensor.set_framesize(sensor.QQVGA) # use QQVGA for speed.
#sensor.skip_frames(10) # Let new settings take affect.
sensor.skip_frames(time =2800)
sensor.set_auto_gain(False) # must be turned off for color tracking
sensor.set_auto_whitebal(False) # turn this off.
clock = time.clock() # Tracks FPS.
K=500#the value should be measured #设定一个距离值,根据该距离值的像素值得到K值 K=20*25
uart = UART(3, 115200)
def find_max(blobs): #寻找最大色块函数
max_size=0
for blob in blobs:
if blob[2]*blob[3] > max_size:
max_blob=blob
max_size = blob[2]*blob[3]
return max_blob
while(True):
clock.tick() # Track elapsed milliseconds between snapshots().
#img = sensor.snapshot() # Take a picture and return the image.
img = sensor.snapshot().lens_corr(1.8)
blobs = img.find_blobs([yellow_threshold]) #颜色识别
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)#像素颜色统计
if 90<statistics.l_mode()<110 and -35<statistics.a_mode()<16 and -28<statistics.b_mode()<20:#if the circle is white
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))#识别到的白色圆形用红色的矩形框出来
else:
img.draw_rectangle(area, color = (255, 255, 255))#将非黑、白色的圆用白色的矩形框出来
if blobs:
max_blob = find_max(blobs) #判断最大的色块是哪个
pan_error = max_blob.cx()-img.width()/2 #下面舵机的左右偏移量
tilt_error = max_blob.cy()-img.height()/2 #上面舵机的上下偏移量
#print("pan_error: ", pan_error)
img.draw_rectangle(max_blob.rect()) # rect
img.draw_cross(max_blob.cx(), max_blob.cy()) # 色块中心点cx, cy #在寻找到的最大色块周围画矩形框
print(pan_error,tilt_error)
pan_output=pan_pid.get_pid(pan_error,1)/2
tilt_output=tilt_pid.get_pid(tilt_error,1) #PID参数
#print("pan_output",pan_output)
pan_servo.angle(pan_servo.angle()+pan_output)
tilt_servo.angle(tilt_servo.angle()-tilt_output) #舵机旋转的角度(控制舵机跟踪色块的中心坐标)
if len(blobs) == 1:# Draw a rect around the blob.
b = blobs[0]
img.draw_rectangle(b[0:4]) # rect
img.draw_cross(b[5], b[6]) # cx, cy
Lm = (b[2]+b[3])/2 #小球的长加宽/2得到LM的值
length = K/Lm
print(length)
head="00"
output_str="[%d,%d,%.2f]" % (pan_error,tilt_error,length) #方式1
print('you send:',output_str)
uart.write(head+'\r\n')
uart.write(output_str+'\r\n')
uart.write(head+'\r\n')
else:
print('not found!')
:folded_hands: :folded_hands: :folded_hands:
看上去缩进不对。
对的,是缩进没对,谢谢啦