基于Openmv的简单巡线(送药小车)

该代码可以识别十字路口,终点线的判断,完成简单巡线的要求,并将数据传给32进行处理

import sensor, image, time,lcd
from pyb import UART

uart = UART(3, 115200, timeout_char=1000)
red_threshold = ((29, 100, 38, 93, -82, 61))#红色阈值
sensor.reset()
sensor.set_pixformat(sensor.RGB565)   #选择RGB模式
sensor.set_framesize(sensor.QQVGA)    #160*120选择分辨率(分辨率越高帧率可能越低)
sensor.skip_frames(time = 2000)
lcd.init()
sensor.set_hmirror(True)#开启镜像
uart.init(115200,8,None,1) #对串口3给定参数初始化
line_roi1 = (25,5,110,10)#上方
#line_roi2 = (25,30,110,10)#中方
line_roi3 = (25,50,110,10)#下方
flag=0 #0正常巡线,1十字路口,2终点线
xx1=0
xx2=0
# 通信协议
def Send_data_packet(data1,data2,data3):#data1 = xx1,data2 = xx2,data3 = flag
    x = '%03d'%data1
    y = '%03d'%data2
    z = '%01d'%data3
    data = 'W'+x+y+z+'Z'
    uart.write(data)

#求绝对值
def my_abs(x,y):
    xx = x - y
    if(xx>0):
        return xx
    else:
        return -xx

def run():#巡线函数
     global flag #  0正常巡线,1十字路口,2终点线
     global xx1
     global xx2
     blobs_low = img.find_blobs([red_threshold], roi = line_roi1,pixels_threshold = 5)
     #blobs_high = img.find_blobs([red_threshold], roi = line_roi3, pixels_threshold = 5)

     if(blobs_low):#前方有线
         if(blobs_low[0].h()*blobs_low[0].w()>=210):#十字路口
             flag = 1
             xx1 = 80
             xx2 = 0
             print("across")
         else:#正常巡线
             img.draw_cross(blobs_low[0].cx(), blobs_low[0].cy(), (0,255,0), 5)
             #img.draw_cross(blobs_high[0].cx(), blobs_high[0].cy(), (255,255,255), 5)
             print("line")
             flag = 0
             xx1 = blobs_low[0].cx()
             xx2=0
     else:#前方无线
         flag = 4
         xx1 = 80
         xx2 = 0
         print("end")

while (True):

    Send_data_packet(xx1,xx2,flag)
    img = sensor.snapshot()
    run()
    img_black=img.binary([red_threshold])#图像二值化,使图像只有黑白,白色为被追踪的颜色,注意: 
                                         #要放在色块识别的后面,不然色块识别会出问题
    lcd.display(img)

你可能感兴趣的:(stm32,单片机,计算机视觉)