用户使用自制 OpenMV4 H7 Plus 模块运行绿色灯珠识别代码,在运行过程中程序无规律崩溃,设备指示灯在所有颜色间爆闪,初步判断为硬件层面异常(如供电不稳、短路、IO冲突或PCB设计问题)。
import sensor
import time
import math
import image
import mjpeg
import pyb
import display
import ujson
import struct
from pyb import UART, LED
usb = pyb.USB_VCP()
t0 = pyb.millis()
while not usb.isconnected():
if pyb.elapsed_micros(t0) > 5000:
break
pyb.delay(10)
def init_sensor():
sensor.reset()
time.sleep_ms(500)
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False,gain_db=-14)
sensor.set_auto_whitebal(False,rgb_gain_db=(65.3575, 60.206, 61.2366))#red
#sensor.set_auto_whitebal(False,rgb_gain_db=(65.1775, 60.206, 61.5255))#blue
sensor.set_brightness(-3)
sensor.set_auto_exposure(False, exposure_us=600)
init_sensor()
# 硬件对象初始化:LED指示灯、串口、LCD显示屏
red_led = LED(1)
green_led = LED(2)
blue_led = LED(3)
uart = UART(3, 115200)
# 录像编号初始化函数:从文件读取上次的录像编号,避免覆盖(第一版机制)
def init_record_suffix():
try:
with open("example_name_suffix.json", "r") as file:
suffix = ujson.load(file)
return suffix if isinstance(suffix, int) and suffix > 0 else 1
except (OSError, ValueError, TypeError):
return 1
example_name_suffix = init_record_suffix()
# ========================== 全局变量定义 ==========================
# 录像相关变量(第一版机制,整合第二版录像参数)
mjpeg_obj = None
recording = False
err_record_file = None
err_record_enabled = False
rec_cnt = 0
sec = 0
RECORD_SKIP = 2
file_index = 0
set_x = -4
set_y = int(sensor.height()*8 / 24)
target_x = int(sensor.width() / 2) + set_x
target_y = int(sensor.height() / 2) + set_y
err_x = 0
err_y = 0
#green_threshold = (26, 100, -87, -33, 34, 81)
#窄
#green_threshold = (11, 100, -128, -16, 1, 81)
#宽
green_threshold = (30, 100, -78, -30, 20, 80)
last_blob = None
last_blob_flag = False
flag_byte = 0 # 保留第一版标志位(关键需求)
# 第一版色块面积参数(保留,兼容机制)
MIN_BLOB_AREA = 2
MAX_BLOB_AREA = 3000
# ========================== 工具函数 ==========================
# 串口发送函数:保留第一版额外字节(frame_header + flag_byte + a + b),满足需求
def send_frame(uart, frame_header, flag_byte, a, b):
header_byte = struct.pack('B', frame_header)
flag_byte_data = struct.pack('B', flag_byte) # 保留额外串口字节
a_bytes = struct.pack('h', a)
b_bytes = struct.pack('h', b)
uart.write(header_byte + flag_byte_data + a_bytes + b_bytes)
def draw_info(img, clock, err_x, err_y, sec):
"""图像信息绘制函数:整合两版绘制逻辑"""
img.draw_string(
sensor.width() - 74, 210,
"USTC-SDC", color=(255, 100, 100), scale=1, x_spacing=0, y_spacing=0, mono_space=True
)
info_text = f"ERR_X:{err_x}\r\nERR_Y:{err_y}"
img.draw_string(
10, 200, info_text, color=(255, 255, 255), scale=1, x_spacing=0, y_spacing=0, mono_space=True
)
info_text = f"FPS:{clock.fps()}\r\nSEC:{sec}"
img.draw_string(
10, 10, info_text, color=(255, 255, 255), scale=1, x_spacing=0, y_spacing=0, mono_space=True
)
img.draw_cross(target_x, target_y, color=(255, 255, 255), size=5, thickness=1
)
img.draw_cross(target_x, 240-90, color=(255, 255, 255), size=2, thickness=1
)
# ========================== 主循环(核心业务逻辑:移除ROI跟踪,保留其他所有逻辑) ==========================
clock = time.clock()
while True:
clock.tick()
img = sensor.snapshot()
err_x = 0
err_y = 0
flag_byte = 0 # 重置标志位
target_found = False
green_led.on()
# ========================== 核心识别逻辑(移除ROI跟踪,仅保留全局搜索) ==========================
# 全局搜索绿色色块(移除ROI分支,只保留原else分支的全局搜索逻辑)
blobs = img.find_blobs(
[green_threshold],
x_stride=1,
y_stride=1,
pixels_threshold=1,
area_threshold=1,
merge=True
)
# -------------------------- 最大色块筛选机制(完全保留) --------------------------
max_area_blob = None # 新增:初始化最大面积色块变量
max_area = 0 # 新增:初始化最大面积阈值
# 遍历绿色色块,先筛选出所有符合条件的色块,再找出其中面积最大的
for blob in blobs:
# 计算圆形度,筛选圆形目标(灯珠)
circularity = blob.pixels() / (max(blob.w(), blob.h()) ** 2)
blob_ratio = blob.w() / blob.h() # 宽高比(宽÷高)
# 原有筛选条件(不变)
if circularity > 0.10 and abs(blob.cx() - target_x) < 200:
# 新增:比较当前色块面积与最大面积,更新最大色块
if blob.area() > max_area:
max_area = blob.area()
max_area_blob = blob
# -------------------------- 使用最大面积色块作为目标(完全保留) --------------------------
if max_area_blob is not None:
err_x = max_area_blob.cx() - target_x
err_y = max_area_blob.cy() - target_y
target_found = True
flag_byte = 1 # 置位标志位(第一版保留需求)
last_blob_flag = True
last_blob = max_area_blob # 记录最大色块(仅保留变量,无ROI跟踪)
# 绘制识别结果
img.draw_circle(max_area_blob.cx(), max_area_blob.cy(), int((max_area_blob.w() + max_area_blob.h()) / 4) , color=(255, 0, 0))
if not target_found:
print("未检测到目标灯珠")
# ========================== 第一版机制(完整保留:串口发送 + 错误记录 + 图像绘制) ==========================
# 串口发送:保留flag_byte额外字节
send_frame(uart, 0xA5, flag_byte, err_x, err_y)
# 错误信息记录(第一版机制)
if err_record_enabled and err_record_file:
err_record_file.write(f"{rec_cnt},{pyb.millis()},{err_x},{err_y}\n")
# 图像信息绘制
draw_info(img, clock, err_x, err_y, sec)
print(sensor.get_rgb_gain_db())
# ========================== 第一版串口指令处理(录像启停,完整保留) ==========================
if uart.any():
try:
cmd = uart.read(1)
if cmd == b'\x37':#0x37
# 开始录像指令
if recording == True:
continue # 已在录像中,忽略重复开始指令
filename = f"example_{example_name_suffix}.mjpeg"
mjpeg_obj = mjpeg.Mjpeg(filename)
recording = True
sec = 0
rec_cnt = 0
err_filename = f"errors_{example_name_suffix}.txt"
err_record_file = open(err_filename, "w")
err_record_enabled = True
file_index += 1 # 同步第二版文件索引
elif cmd == b'\x5A':
# 停止录像指令
if recording and mjpeg_obj:
mjpeg_obj.close()
green_led.off()
blue_led.on()
red_led.on()
green_led.off()
recording = False
example_name_suffix += 1
# 保存录像编号,避免覆盖
with open("example_name_suffix.json", "w") as file:
ujson.dump(example_name_suffix, file)
if err_record_file:
err_record_file.close()
err_record_file = None
err_record_enabled = False
except OSError as e:
print(f"指令处理异常: {e}")
green_led.off()
red_led.on()
time.sleep_ms(100)
red_led.off()
# ========================== 第一版录像时长控制(整合第二版自动停止参数) ==========================
if recording:
rec_cnt += 1
if (rec_cnt % RECORD_SKIP) == 0:
mjpeg_obj.write(img)
sec += 1
# 自动停止录像:第二版800秒阈值,兼容第一版逻辑
if sec >= 800:
mjpeg_obj.close()
recording = False
example_name_suffix += 1
with open("example_name_suffix.json", "w") as file:
ujson.dump(example_name_suffix, file)
if err_record_file:
err_record_file.close()
err_record_file = None
err_record_enabled = False
print(f"录像已保存为 example_{example_name_suffix-1}.mjpeg")
小助手这边测试可以正常运行
测试环境为裸OpenMV,没有连接如何外设