程序如下,不知道为什么一运行就报错,内存超了,可以怎么修改呀在保留原本功能的情况下
固件版本 0.4.0
import os, time, gc
from media.sensor import *
from media.display import *
from media.media import *
from machine import TOUCH
from Mylib.key import KeyButton
WIDTH, HEIGHT = 800, 480 # 保持原分辨率
key = KeyButton()
roi1 = (200, 120, 450, 250) # 保持原ROI
threshold = [15, 228] # 保持原阈值
black_threshold = [threshold]
sensor = Sensor()
sensor.reset()
sensor.set_framesize(chn=CAM_CHN_ID_0, width=WIDTH, height=HEIGHT)
sensor.set_pixformat(Sensor.RGB565, chn=CAM_CHN_ID_0)
sensor.set_framesize(chn=CAM_CHN_ID_1, width=WIDTH, height=HEIGHT)
sensor.set_pixformat(Sensor.RGB565, chn=CAM_CHN_ID_1)
Display.init(Display.ST7701, width=WIDTH, height=HEIGHT, to_ide=True)
MediaManager.init()
sensor.run()
tp = TOUCH(0)
status_text = ""
exit_text = "按按键退出"
try:
while True:
os.exitpoint()
gc.collect()
# 检查退出条件
if key.is_rising_edge():
print("退出黑色胶带检测")
break
# 通道1用于识别处理
img_roi = sensor.snapshot(chn=CAM_CHN_ID_1)
img_roi.to_grayscale(inplace=True)
# 通道0用于显示
display_img = sensor.snapshot(chn=CAM_CHN_ID_0)
# 图像处理(使用原地操作)
img_roi.binary(black_threshold, inplace=True)
img_roi.dilate(1, inplace=True)
img_roi.erode(1, inplace=True)
# 检测外轮廓矩形
outer_rects = []
if roi1 is not None and isinstance(roi1, (tuple, list)) and len(roi1) == 4:
outer_rects = img_roi.find_rects(roi=roi1)
else:
outer_rects = img_roi.find_rects()
outer_rect = None
inner_rect = None
if outer_rects:
# 筛选最大的外矩形
outer_rect = max(outer_rects, key=lambda r: r.w() * r.h())
x, y, w, h = outer_rect.rect()
display_img.draw_rectangle(x, y, w, h, color=(255, 0, 0), thickness=2)
# 尝试检测内部矩形
padding = 3
min_x, max_x = x + padding, x + w - padding
min_y, max_y = y + padding, y + h - padding
if min_x < max_x and min_y < max_y:
inner_rects = img_roi.find_rects(roi=(min_x, min_y, max_x - min_x, max_y - min_y))
if inner_rects:
# 筛选最大的内矩形
inner_rect = max(inner_rects, key=lambda r: r.w() * r.h())
ix, iy, iw, ih = inner_rect.rect()
display_img.draw_rectangle(ix, iy, iw, ih, color=(0, 0, 255), thickness=2)
# 更新状态文本
if outer_rect and inner_rect:
status_text = "胶带检测中: 已识别内外矩形"
status_color = (0, 255, 0)
elif outer_rect:
status_text = "胶带检测中: 仅识别外矩形"
status_color = (255, 255, 0)
else:
status_text = "胶带检测中: 未识别"
status_color = (255, 0, 0)
# 绘制状态信息
display_img.draw_string_advanced(10, 10, 20, status_text, status_color)
# 绘制退出提示
display_img.draw_string_advanced(WIDTH - 200, HEIGHT - 30, 18, exit_text, (255, 255, 255))
# 显示图像
Display.show_image(display_img)
del display_img
del img_roi
gc.collect()
time.sleep_ms(50)
except KeyboardInterrupt:
print("程序被用户中断")
except BaseException as e:
print(f"[ERROR] 出现异常: {e}")
finally:
# 释放资源
try:
sensor.stop()
Display.deinit()
MediaManager.deinit()
except:
pass
gc.collect()
print("资源已释放")