OPENMV巡线转弯代码 优化版2022.6.29
大四毕业了,用不到了,这几天趁着闲优化了一下,之前那个号写的太复杂了
- OPENMV通过UART进行通信
- ROIS为5块感性区域,在160x120范围内分为5块,方便遇到路口和前方无道路的处理
- largest_blob为blob模块[2]为色块w,[3]为色块h,官方docs上有说明
- 对out_str进行设置可看到串口输出的内容
- 然后就是一些变量有用没用的自己使用的时候删一下,这一份的逻辑还是存在问题的
- 本人将此代码用于2021送药小车复现配合K210数字识别复现成功
- 直接复制粘贴就能用,不能用的自己反思一下自己是不是啥都不会
import sensor, image, time, math,pyb
from pyb import Pin, Timer,UART
uart = pyb.UART(1,115200,timeout_char = 1000)
Red_Thresholds = [(33, 61, 16, 85, 21, 69)]
ROIS = [
(30, 90, 100, 30, 0),
(40, 40, 80, 40, 0),
(30, 0, 100, 30, 0),
(0, 20, 30, 100, 0),
(130,20 , 30, 100, 0)
]
weight_sum = 0
for r in ROIS: weight_sum += r[4]
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
flag=0;
i=0;
j=0;
led=pyb.LED(3)
cross_num = 0
cross_flag = 0
back_flag = 0;
center_flag1 = 0
center_flag2 = 0
center_flag3 = 0
center_flag4 = 0
center_flag5 = 0
out_str1='';
clock = time.clock()
old_img= sensor.snapshot().mean_pooled(4,4)
def tick(timer):
global flag
flag=1
tim = Timer(4,freq=100)
tim.callback(tick)
while(True):
pyb.LED(1).on()
if(flag==1):
img=sensor.snapshot()
img.lens_corr(1.5)
for r in ROIS:
i=i+1;
blobs=img.find_blobs(Red_Thresholds, roi=r[0:4], merge=True,pixels_area=10)
if blobs:
largest_blob = max(blobs, key=lambda b: b.pixels())
if(i==1):
if(largest_blob[2]>=5):
if(largest_blob[3]>=5):
center_flag1=1;
img.draw_rectangle(largest_blob.rect())
img.draw_cross(largest_blob.cx(),largest_blob.cy(),2)
elif(i==2):
if(largest_blob[2]>=5):
if(largest_blob[3]>=5):
center_flag2=1;
img.draw_rectangle(largest_blob.rect())
img.draw_cross(largest_blob.cx(),largest_blob.cy(),2)
elif(i==3):
center_flag3=2;
if(largest_blob[2]>=5):
if(largest_blob[3]>=5):
center_flag3=1;
img.draw_rectangle(largest_blob.rect())
img.draw_cross(largest_blob.cx(),largest_blob.cy(),2)
elif(i==4):
if(largest_blob[2]>=5):
if(largest_blob[3]>=5):
center_flag4=1;
img.draw_rectangle(largest_blob.rect())
img.draw_cross(largest_blob.cx(),largest_blob.cy(),2)
elif(i==5):
if(largest_blob[2]>=5):
if(largest_blob[3]>=5):
center_flag5=1;
img.draw_rectangle(largest_blob.rect())
img.draw_cross(largest_blob.cx(),largest_blob.cy(),2)
if(center_flag2>0 and center_flag4>0 and center_flag5>0):
cross_num = cross_num + 1
if(cross_num>0 and center_flag2==0 and center_flag4==0 and center_flag5==0 and center_flag3==0):
back_flag = 1
i=0;
out_str1+='%.d'% int(center_flag1);
out_str1+='%.d'% int(center_flag2);
out_str1+='%.d'% int(center_flag3);
out_str1+='%.d'% int(center_flag4);
out_str1+='%.d'% int(center_flag5);
out_str1+='%.4d'% int(cross_num);
out_str1+='%.d'% int(back_flag);
uart.write('s'+out_str1+'#')
print(out_str1)
turn_flag=0;
center_flag1 = 0
center_flag2 = 0
center_flag3 = 0
center_flag4 = 0
center_flag5 = 0
out_str1=''
flag=0;