MicroPython(OpenMV)如何实现未检测到对象时的代码逃逸路径
问题原因
你遇到的ArilY is not defined报错和分支逻辑失效,由5个核心问题导致:
- 作用域错误:
aril/seed是for循环内部的临时变量,对应色块没被检测到时循环不会执行,变量根本不存在,直接访问就会抛未定义错误;且func_pass/func_fail在全局位置访问循环内的临时变量,必然触发报错 - 执行位置错误:
func_orientation()的调用写在了while(True)检测循环外面,程序启动后只会执行1次,不会跟着每帧画面跑检测 - 状态残留:
arilY/seedY/rapheY每轮检测前没有重置为空值,会沿用上一帧的检测结果,出现误判 - 语法错误:
func_orientation内部的判断逻辑缩进错误、朝向判定的if条件缺失 - 空分支缺失:没有写未检测到目标时的跳过逻辑,检测不到物体时还是会跑朝向校验流程
修复后可直接运行的代码
import sensor, image, time, math from pyb import UART sensor.reset() # 复位初始化摄像头 sensor.set_pixformat(sensor.RGB565) # 设置图像格式为RGB565 sensor.set_framesize(sensor.QVGA) # 设置分辨率320x240 sensor.skip_frames(time = 2000) # 等待设置生效 # 颜色追踪时需关闭自动增益、自动白平衡 #sensor.set_auto_gain(False) #sensor.set_auto_whitebal(False) # 色块阈值 threshold_seed = (7,24,-8,4,-3,9) threshold_aril = (33,76,-14,6,17,69) threshold_raphe = (36,45,28,43,17,34) clock = time.clock() # 帧率统计时钟 uart = UART(3, 9600) # 初始化串口3,波特率9600 # 全局变量存储检测结果 arilY = None arilX = None seedY = None rapheY = None def func_pass(): result = "Pass" print(result) print("%d\n"%arilX, end='') uart.write(result) uart.write("%d\n"%arilX) def func_fail(): result = "Fail" print(result) print("%d\n"%arilX, end='') uart.write(result) uart.write("%d\n"%arilX) def func_orientation(seedY, arilY): # 两个核心色块都检测到才执行判断 if seedY is not None and arilY is not None: # 朝向判定规则:seed在aril上方(Y坐标更小)判定为Pass,可根据实际需求调整判断条件 if seedY < arilY: func_pass() else: func_fail() while(True): clock.tick() img = sensor.snapshot() # 每帧检测前重置所有检测结果为空,避免上一帧数据干扰 arilY = None arilX = None seedY = None rapheY = None # 检测seed色块 for seed in img.find_blobs([threshold_seed], pixels_threshold=200, area_threshold=200, merge=True): img.draw_rectangle(seed[0:4]) img.draw_cross(seed.cx(), seed.cy()) img.draw_string(seed.x()+2,seed.y()+2,"seed") seedY = seed.cy() # 检测aril色块 for aril in img.find_blobs([threshold_aril],pixels_threshold=300,area_threshold=300, merge=True): img.draw_rectangle(aril[0:4]) img.draw_cross(aril.cx(),aril.cy()) img.draw_string(aril.x()+2,aril.y()+2,"aril") arilY = aril.cy() arilX = aril.cx() # 检测raphe色块 for raphe in img.find_blobs([threshold_raphe],pixels_threshold=300,area_threshold=300, merge=True): img.draw_rectangle(raphe[0:4]) img.draw_cross(raphe.cx(),raphe.cy()) img.draw_string(raphe.x()+2,raphe.y()+2,"raphe") rapheY = raphe.cy() # 空值判断:缺核心检测对象直接打印提示进入下一轮 if seedY is None or arilY is None: print("未检测到目标对象") continue # 执行朝向判定 func_orientation(seedY, arilY)
关键修改说明
- 每帧开始检测前将所有存储坐标的变量重置为
None,避免上一帧旧数据干扰当前帧判断 - 新增空值判断分支:只要seed或aril任意一个核心色块没检测到,直接打印提示后用
continue跳过后续判定,进入下一轮循环,从根源避免未定义报错 - 将
func_orientation调用移入循环内部,保证每帧画面采集完成后都执行检测逻辑 - 把需要跨作用域访问的aril X坐标单独存为全局变量,解决局部变量跨作用域访问的报错问题
- 补全了朝向判定的条件逻辑、修复了所有缩进错误,可根据实际朝向规则调整
seedY < arilY这个判断条件
内容的提问来源于stack exchange,提问作者Hannah Reigi
相关产品推荐
相关产品推荐

