openmv循迹
希望我们队电赛可以取得好成绩
main.py
THRESHOLD = (5, 70, -23, 15, -57, 0) # 如果追踪其他颜色的线,就要修改阈值
import sensor, time
from pyb import LED
import car
from pid import PID
rho_pid = PID(p=0.4, i=0)#y=ax+b b
#控制线在视野中,距离的偏移
theta_pid = PID(p=0.001, i=0)#a
#如果发现车偏移的比较大或者,转弯转的比较大
#我们相应的减少两个pid的值即可
LED(1).on()
LED(2).on()
LED(3).on()
#打开RGB灯,用来补光,保持环境稳定
sensor.reset()
sensor.set_vflip(True)#垂直方向的翻转
sensor.set_hmirror(True)#水平方向的翻转
#倒着安装的,在图像中正过来
sensor.set_pixformat(sensor.RGB565)#设置追踪颜色的图像色彩为彩图
sensor.set_framesize(sensor.QQQVGA) # 80x60 (4,800 pixels) - O(N^2) max = 2,3040,000.
#sensor.set_windowing([0,20,80,40])
#巡线使用的是get_regression线性回归方法,运算量大
#越小的分辨率,识别的效果越好,速度越快
sensor.skip_frames(time = 2000) # WARNING: If you use QQVGA it may take seconds
clock = time.clock() # to process a frame sometimes.
while(True):
clock.tick()
img = sensor.snapshot().binary([THRESHOLD])
#对图片进行阈值分割
#img.binary将中间的蓝线分割成白色,非蓝色的线分割成黑色
#将图像进行二值化
line = img.get_regression([(100,100)], robust = True)
#对所有的函数阈值进行像素回归
#线性回归的效果就是,将视野中二值化分割后的图像,回归成一条直线
#x_stride设置进行操作的时候需要跳过的x方向上的像素点,一般使用默认的值即可
if (line):
rho_err = abs(line.rho())-img.width()/2
#计算得到的这一条直线与图像中央偏移的距离
if line.theta()>90:
theta_err = line.theta()-180
else:
theta_err = line.theta()
#进行了坐标的变换
img.draw_line(line.line(), color = 127)
#把得到的直线画出来
print(rho_err,line.magnitude(),rho_err)
if line.magnitude()>8:
#if -40<b_err<40 and -30<t_err<30:
rho_output = rho_pid.get_pid(rho_err,1)
#把直线调到视野的中央
theta_output = theta_pid.get_pid(theta_err,1)
#把直线调整到与y轴平行的方向
output = rho_output+theta_output
#利用最后的参数来控制电机的运动
car.run(50+output, 50-output)
#以中央速度50为基准值进行加减
#car.run这个函数里面,电机运动的速度是0-100
#想要它快一点,可以设置成70
else:
car.run(0,0)#效果不好,停止运动
else:
car.run(50,-50)
pass
#如果在视野中发现没有线,原地旋转
#print(clock.fps())