logo

我想通过判断小球在openmv什么方向,通过串口发送字符串控制小车,为什么最后判断距离出现了图片的问题并且显示a未定义?

2023-03-07 16:10
1
cmvs
e59d1260-0553-4d3a-929e-d1e7f0e81198.png
import sensor, image , time  #导入摄像头,机器视觉,时间模块
from pyb import UART,LED     #从pyb中导入UART(串口)模块,LED模块
import ustruct
import json

#开启LED灯
LED(1).on()
LED(2).on()
LED(3).on()

#摄像头设置
sensor.reset()               #Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565)#use RGB565.
sensor.set_framesize(sensor.QVGA) #use QQVGA for speed.
sensor.skip_frames(10)       #Let new settings take affect.
sensor.set_auto_whitebal(False) #turn this off.
clock = time.clock()             #Tracks EPS

yellow_threshold = ( 46,  100,  -68,   72,   58,   92) #颜色阙值设置(此处为红色颜色阀值)
size_threshold = 9000 #目标色块面积设置

uart = UART (3,115200)#定义串口3变量
uart.init(115200, bits=8, parity=None, stop=1) #串口初始化设置
#寻找最大色块函数
def find_max(blobs):
    max_size=0
    for blob in blobs:
        if blob[2]*blob[3] > max_size:
            max_blob=blob
            max_size = blob[2]*blob[3]
    return max_blob


while(True):
    clock.tick() #时钟设置
    img = sensor.snapshot() #获取一张图像

    blobs = img.find_blobs ([yellow_threshold]) #调用寻找色块函数

#找到目标颜色色块
    if blobs:
        max_blob = find_max (blobs) #找到目标颜色物体中面积最大的物体
        x_error = max_blob[5] #目标颜色物体的中心横坐标
        y_error = max_blob[6]
        width = max_blob[2]#目标颜色物体的宽度
        hight = max_blob[3]#目标颜色物体的高度

        img.draw_rectangle(max_blob[0:4]) #用方块圈出目标颜色物体
        img.draw_cross(max_blob[5],max_blob[6]) #对目标颜色物体画十字

        x_error = round(x_error) #对目标颜色物体的中心横坐标取整数
        y_error = round(y_error)
        width = round(width)#目标颜色物体的宽度取整数
        hight = round(hight)#目标颜色物体的高度取整数
        a = x_error-width /2#计算出小球边缘靠左还是靠右
        print("x error and y error and width and hight and a :",x_error,y_error,width,hight,a)
    elif a<=77:
        uart.write('1')#距离小于77给串口发送1
        print('1')
    elif(a>=227):
        uart.write('2')#距离大于227给串口发送2
        print('2')
    elif(a>77 and a<227):
        uart.write('3')#距离在77-227之间给串口发送3
        print('3')

    else:
        uart.write ('0') #没找到目标颜色物体通过串口发送字符1
        print ('0')
2023-03-07 18:53
I
网红小智智 星瞳科技

41行上面,加一行a=0