OpenMV识别色块并且与STM32串口通信

mac2022-06-30  81

任务

比赛要求在三个不同颜色的球球中,识别绿球球的位置,并且用机械臂抓取。然后在通过门之后,识别路标,判断左右转。

串口通信

OpenMV与STM32通信的方式是串口通信,使用openmv简单的串口配置。 因为视觉部分有两个任务,所以用单片机给STM32发送“1”,开始颜色识别,发送“2”,开始特征点识别。不发送则不识别。

我串口一开始使用了正点原子的STM32精英板,串口就是发不出来,串口程序看了无数遍,心里想,自己虽然菜,但是串口还是能写的吧。

直到后来发现没有加跳线帽,感叹一下自己好蠢。

识别色块

代码使用了OpenMV内置函数来找色块,并且把红绿蓝三个颜色的中心位置保存起来,进行比较,串口输出绿球球所处的位置。 还没有写特征点识别的内容。

玄学报错

OpenMV在编译的过程中,如果没有变量提前初始化,直接写

cx = blob.cx()

会出现一定概率的报错,之前调试的过程中,大约60%的几率可以运行,40%的几率编译器会报错,这种同一片代码,同一个编译器,每次运行结果不同,我还是第一次遇到,解决方法也很简单只需要在使用变量前提前初始化即可,报错就不会出现了。有趣而又玄妙的OpenMV!! 虽然解决之后感觉简单,但是最后加上这句话花了我大概三天!!太恶心了!!

cx = 0

随后附上代码

import sensor, image, time, math from pyb import UART threshold_index = 0 thresholds = thresholds = [(11, 15, 19, 35, -27, 35), #red (7, 17, -73, 14, -46, -16), #blue (11, 68, -87, -22, -27, 58)] #green sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time = 2000) sensor.set_auto_gain(False) # must be turned off for color tracking sensor.set_auto_whitebal(False) # must be turned off for color tracking clock = time.clock() def draw_keypoints(img, kpts): if kpts: print(kpts) img.draw_keypoints(kpts) img = sensor.snapshot() time.sleep(1000) #初始化串口 uart = UART(3, 115200) uart.init(115200, bits=8, parity=None, stop=1) #初始化变量 x = 0 Res = 0 green_position = 0 send_1 = 0 #颜色识别模块发送的内容 send_2 = 0 #特征点匹配模块发送的内容 x_red = 0 x_blue = 0 x_green = 0 Num_Blob = 0 while(True): if (uart.any()) : R=uart.readline().decode().strip() Res = int(R) #print(Res) #设定openmv模式,1为颜色识别,2为特征点匹配 #uart.writechar("Res") if(Res == 1): clock.tick() img = sensor.snapshot() #for blob in img.find_blobs(thresholds, pixels_threshold=200, area_threshold=200): #if(blob.code()==7): for blob in img.find_blobs([thresholds[0]], pixels_threshold=200, area_threshold=200): x_red = blob.cx() for blob in img.find_blobs([thresholds[1]], pixels_threshold=200, area_threshold=200): x_blue = blob.cx() for blob in img.find_blobs([thresholds[2]], pixels_threshold=200, area_threshold=200): x_green = blob.cx() if(x_green < x_red and x_green < x_blue): send_1 = 1 elif(x_green > x_red and x_green < x_blue): send_1 = 2 elif(x_green < x_red and x_green > x_blue): send_1 = 2 elif(x_green > x_red and x_green > x_blue): send_1 = 3 #发串口 uart.write('%d' %(send_1)) Res = 0 if(Res == 2): uart.write('%d' %(send_2)) Res = 0
最新回复(0)