openmv,巡线两条黄线,如果有一条黄线突然没有了怎么靠另一条黄线寻线,但不影响啊后来的两条黄线巡线
时间: 2024-03-17 22:44:27 浏览: 184
以下是一个完整的 OpenMV 巡线代码,可以巡线两条黄线,并在一条黄线消失时通过另一条黄线进行寻线,同时不影响后来的两条黄线巡线。
```python
import sensor
import image
import time
import math
# 设置巡线阈值
GRAYSCALE_THRESHOLD = (200, 255)
# 设置寻线偏移量
OFFSET = 30
# 设置两条黄线的最小距离
MIN_DIST = 50
# 初始化摄像头
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
# 初始化PID控制器
kp = 0.5
kd = 0.1
last_error = 0
# 记录上一次检测到的黄线
last_line1 = None
last_line2 = None
# 巡线
while True:
# 获取图像
img = sensor.snapshot()
# 查找两条黄线
line1 = None
line2 = None
for l in img.find_lines(threshold = 1000, theta_margin = 25, rho_margin = 25):
if l.y1() < 60 or l.y2() < 60:
continue
if abs(l.theta()) < 60:
line1 = l
elif abs(l.theta()) > 120:
line2 = l
# 如果只有一条黄线,通过偏移量寻找另一条黄线
if line1 is not None and line2 is None:
line2_x = line1.x1() + (line1.x2() - line1.x1()) * (120 if line1.theta() < 0 else -120) / line1.theta()
line2_y = line1.y1() + (line1.y2() - line1.y1()) * (120 if line1.theta() < 0 else -120) / line1.theta()
line2 = (line2_x, line2_y, line1.x2(), line1.y2())
# 如果两条黄线都存在,计算偏差值并进行PID控制
if line1 is not None and line2 is not None:
# 计算两条黄线的距离
dist = math.sqrt((line1.x1() - line2.x1()) ** 2 + (line1.y1() - line2.y1()) ** 2)
# 如果两条黄线的距离小于最小距离,忽略掉其中一条黄线
if dist < MIN_DIST:
if last_line1 is None or last_line2 is None:
continue
elif line1 == last_line1 and line2 == last_line2:
continue
elif line1 == last_line2 and line2 == last_line1:
continue
elif last_line1 is not None and last_line2 is not None:
if dist < math.sqrt((last_line1.x1() - last_line2.x1()) ** 2 + (last_line1.y1() - last_line2.y1()) ** 2):
line1 = last_line1
line2 = last_line2
# 计算机器人偏离中心线的距离
error = (line1.x1() + line2.x1() - img.width()) / 2
# 计算PID控制值
pid = error * kp + (error - last_error) * kd
last_error = error
# 控制机器人行驶
if abs(pid) > OFFSET:
if pid > 0:
# 左转
pass
else:
# 右转
pass
else:
# 直行
pass
# 更新上一条黄线
last_line1 = line1
last_line2 = line2
```
在这个例子中,我们添加了一个新的变量 `last_line1` 和 `last_line2` 来记录上一次检测到的黄线。当检测到两条黄线的距离小于最小距离时,我们会比较当前检测到的黄线和上一次检测到的黄线,选择距离更远的两条黄线进行巡线,同时忽略掉重复的情况。这样可以避免在一条黄线消失后立即切换到另一条黄线,从而影响后来的两条黄线巡线。
阅读全文