使用嘉立创矩形检测例程,报错:异常: Out of fast frame buffer stack memory

Viewed 158

嘉立创矩形识别例程如下:
import time, os, sys

from media.sensor import *
from media.display import *
from media.media import *

picture_width = 400
picture_height = 240

sensor_id = 2
sensor = None

显示模式选择:可以是 "VIRT"、"LCD" 或 "HDMI"

DISPLAY_MODE = "LCD"

根据模式设置显示宽高

if DISPLAY_MODE == "VIRT":
# 虚拟显示器模式
DISPLAY_WIDTH = ALIGN_UP(1920, 16)
DISPLAY_HEIGHT = 1080
elif DISPLAY_MODE == "LCD":
# 3.1寸屏幕模式
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 480
elif DISPLAY_MODE == "HDMI":
# HDMI扩展板模式
DISPLAY_WIDTH = 1920
DISPLAY_HEIGHT = 1080
else:
raise ValueError("未知的 DISPLAY_MODE,请选择 'VIRT', 'LCD' 或 'HDMI'")

try:
# 构造一个具有默认配置的摄像头对象
sensor = Sensor(id=sensor_id)
# 重置摄像头sensor
sensor.reset()

# 无需进行镜像翻转
# 设置水平镜像
# sensor.set_hmirror(False)
# 设置垂直翻转
# sensor.set_vflip(False)

# 设置通道0的输出尺寸为1920x1080
sensor.set_framesize(width=picture_width, height=picture_height, chn=CAM_CHN_ID_0)
# 设置通道0的输出像素格式为RGB565
sensor.set_pixformat(Sensor.RGB565, chn=CAM_CHN_ID_0)

# 根据模式初始化显示器
if DISPLAY_MODE == "VIRT":
    Display.init(Display.VIRT, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, fps=60)
elif DISPLAY_MODE == "LCD":
    Display.init(Display.ST7701, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, to_ide=True)
elif DISPLAY_MODE == "HDMI":
    Display.init(Display.LT9611, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, to_ide=True)

# 初始化媒体管理器
MediaManager.init()
# 启动传感器
sensor.run()

while True:
    os.exitpoint()

    # 捕获通道0的图像
    img = sensor.snapshot(chn=CAM_CHN_ID_0)

    # 查找线段并绘制
    rects = img.find_rects(threshold=5000)
    count = 0  # 初始化线段计数器

    print("------矩形统计开始------")
    for rect in rects:
         # 若想获取更详细的四个顶点,可使用 rect.corners(),该函数会返回一个有四个元祖的列表,每个元组代表矩形的四个顶点,从左上角开始,按照顺时针排序。
        img.draw_rectangle(rect.rect(), color=(1, 147, 230), thickness=3)  # 绘制线段
        print(f"Rect {count}: {rect}")  # 打印线段信息
        count += 1  # 更新计数器
    print("---------END---------")

    # 显示捕获的图像,中心对齐,居中显示
    Display.show_image(img, x=int((DISPLAY_WIDTH - picture_width) / 2), y=int((DISPLAY_HEIGHT - picture_height) / 2))

except KeyboardInterrupt as e:
print("用户停止: ", e)
except BaseException as e:
print(f"异常: {e}")
finally:
# 停止传感器运行
if isinstance(sensor, Sensor):
sensor.stop()
# 反初始化显示模块
Display.deinit()
os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
time.sleep_ms(100)
# 释放媒体缓冲区
MediaManager.deinit()
报如下错误:Out of fast frame buffer stack memory
甚至昨天能好好运行的代码,今天就报这个错误运行不了了
硬件平台为庐山派,固件版本和CanMVIDE均为最新版本,

4 Answers
import time, os, sys, gc
from media.sensor import *
from media.display import *
from media.media import *

picture_width = 400
picture_height = 240

sensor_id = 2
sensor = None

# 显示模式选择:可以是 "VIRT"、"LCD" 或 "HDMI"
DISPLAY_MODE = "LCD"

# 根据模式设置显示宽高
if DISPLAY_MODE == "VIRT":
    # 虚拟显示器模式
    DISPLAY_WIDTH = ALIGN_UP(1920, 16)
    DISPLAY_HEIGHT = 1080
elif DISPLAY_MODE == "LCD":
    # 3.1寸屏幕模式
    DISPLAY_WIDTH = 800
    DISPLAY_HEIGHT = 480
elif DISPLAY_MODE == "HDMI":
    # HDMI扩展板模式
    DISPLAY_WIDTH = 1920
    DISPLAY_HEIGHT = 1080
else:
    raise ValueError("未知的 DISPLAY_MODE,请选择 'VIRT', 'LCD' 或 'HDMI'")


# 构造一个具有默认配置的摄像头对象
sensor = Sensor(id=sensor_id)
sensor.reset()

# 可选设置(若需要)
# sensor.set_hmirror(False)
# sensor.set_vflip(False)

# 设置图像参数
sensor.set_framesize(width=picture_width, height=picture_height, chn=CAM_CHN_ID_0)
sensor.set_pixformat(Sensor.RGB565, chn=CAM_CHN_ID_0)

# 初始化显示器
if DISPLAY_MODE == "VIRT":
    Display.init(Display.VIRT, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, fps=60)
elif DISPLAY_MODE == "LCD":
    Display.init(Display.ST7701, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, to_ide=True)
elif DISPLAY_MODE == "HDMI":
    Display.init(Display.LT9611, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, to_ide=True)

# 初始化媒体管理器
MediaManager.init()

# 启动传感器
sensor.run()

while True:
    os.exitpoint()

    # 捕获图像
    img = sensor.snapshot(chn=CAM_CHN_ID_0)

    # 查找矩形
    rects = img.find_rects(threshold=5000)
    count = 0

    print("------矩形统计开始------")
    for rect in rects:
        img.draw_rectangle(rect.rect(), color=(1, 147, 230), thickness=3)
        print(f"Rect {count}: {rect}")
        count += 1
    print("---------END---------")

    # 居中显示图像
    Display.show_image(img, x=(DISPLAY_WIDTH - picture_width) // 2,
                            y=(DISPLAY_HEIGHT - picture_height) // 2)
    gc.collect()

if isinstance(sensor, Sensor):
    sensor.stop()
Display.deinit()
os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
time.sleep_ms(100)
MediaManager.deinit()

你好,可以参考这个脚本。

仍然报这个错误,而且报这个错误有很大的随机性,我尝试按复位键后再执行程序,仍然报错

你烧录的是哪个版本的固件啊

LCKFB_v1.3_0 nncase_2.9.0

sensor.set_framesize(width=800, height=640) #设置帧大小,默认通道0

while True:
clock.tick()

# 拍摄一帧图像 / Capture a frame
img = sensor.snapshot()
img_np = img.to_numpy_ref()  # 获取 RGB888 ndarray 引用

# 调用 cv_lite 扩展的霍夫圆检测函数,返回圆参数列表 [x, y, r, ...]
circles = cv_lite.rgb888_find_circles(
    image_shape, img_np, dp, minDist, param1, param2, minRadius, maxRadius
)
# 遍历检测到的圆形,绘制圆形框
for i in range(0, len(circles), 3):
    x = circles[i]
    y = circles[i + 1]
    r = circles[i + 2]
    img.draw_circle(x, y, r, color=(255, 0, 0), thickness=2)  # 红色圆圈
# 截取中间显示
img_resize = img.copy(roi=(240, 120, 320, 240))
Display.show_image(img_resize, x=240, y=120)

找到问题了,参考下面这个代码

============================================================

MicroPython 基于 cv_lite 的 RGB888 霍夫圆检测测试代码

RGB888 Hough Circle Detection Test using cv_lite extension

============================================================

import time, os, sys, gc
from machine import Pin
from media.sensor import * # 导入摄像头接口 / Camera interface
from media.display import * # 导入显示接口 / Display interface
from media.media import * # 导入媒体资源管理器 / Media manager
import _thread
import cv_lite # 导入 cv_lite 扩展模块 / cv_lite extension
import ulab.numpy as np # MicroPython 类 NumPy 库

-------------------------------

图像尺寸设置 / Image resolution

-------------------------------

image_shape = [480, 800] # 高 x 宽 / Height x Width
frame_shape = [240, 320] # 高 x 宽 / Height x Width

-------------------------------

初始化摄像头(RGB888格式) / Initialize camera (RGB888 format)

-------------------------------

sensor = Sensor(id=2, width=1280, height=720)
sensor.reset()
sensor.set_framesize(width=320, height=240) #设置帧大小,默认通道0
sensor.set_pixformat(Sensor.RGB888) # 设置 RGB888 像素格式 / Set RGB888 pixel format

-------------------------------

初始化显示器(IDE虚拟显示) / Initialize display (IDE virtual output)

-------------------------------

Display.init(Display.ST7701, width=image_shape[1], height=image_shape[0], to_ide=True, quality=100)

-------------------------------

初始化媒体资源管理器 / Initialize media manager

-------------------------------

MediaManager.init()
sensor.run()

-------------------------------

启动帧率计时器 / Start FPS timer

-------------------------------

clock = time.clock()

-------------------------------

霍夫圆检测参数 / Hough Circle parameters

-------------------------------

dp = 1 # 累加器分辨率与图像分辨率的反比 / Inverse ratio of accumulator resolution
minDist = 30 # 检测到的圆心最小距离 / Minimum distance between detected centers
param1 = 80 # Canny边缘检测高阈值 / Higher threshold for Canny edge detection
param2 = 20 # 霍夫变换圆心检测阈值 / Threshold for center detection in accumulator
minRadius = 10 # 检测圆最小半径 / Minimum circle radius
maxRadius = 50 # 检测圆最大半径 / Maximum circle radius

-------------------------------

主循环 / Main loop

-------------------------------

while True:
clock.tick()

# 拍摄一帧图像 / Capture a frame
img = sensor.snapshot()
img_np = img.to_numpy_ref()  # 获取 RGB888 ndarray 引用

# 调用 cv_lite 扩展的霍夫圆检测函数,返回圆参数列表 [x, y, r, ...]
circles = cv_lite.rgb888_find_circles(
    frame_shape, img_np, dp, minDist, param1, param2, minRadius, maxRadius
)
# 遍历检测到的圆形,绘制圆形框
for i in range(0, len(circles), 3):
    x = circles[i]
    y = circles[i + 1]
    r = circles[i + 2]
    img.draw_circle(x, y, r, color=(255, 0, 0), thickness=2)  # 红色圆圈
# 显示带有检测圆的图像 / Display image with circles drawn
#img_resize = img.copy(roi=(240, 120, 320, 240))
Display.show_image(img, x=240, y=120)
# 垃圾回收 / Garbage collect
gc.collect()

# 打印帧率 / Print FPS
print("findcircles:", clock.fps())

-------------------------------

程序退出时释放资源 / Cleanup on exit

-------------------------------

sensor.stop()
Display.deinit()
os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
time.sleep_ms(100)
MediaManager.deinit()

参考下面的代码

# ============================================================
# MicroPython 基于 cv_lite 的 RGB888 霍夫圆检测测试代码
# RGB888 Hough Circle Detection Test using cv_lite extension
# ============================================================

import time, os, sys, gc
from machine import Pin
from media.sensor import *    # 导入摄像头接口 / Camera interface
from media.display import *   # 导入显示接口 / Display interface
from media.media import *     # 导入媒体资源管理器 / Media manager
import _thread
import cv_lite                # 导入 cv_lite 扩展模块 / cv_lite extension
import ulab.numpy as np       # MicroPython 类 NumPy 库

# -------------------------------
# 图像尺寸设置 / Image resolution
# -------------------------------
image_shape = [480, 800]  # 高 x 宽 / Height x Width
frame_shape = [240, 320]  # 高 x 宽 / Height x Width

# -------------------------------
# 初始化摄像头(RGB888格式) / Initialize camera (RGB888 format)
# -------------------------------
sensor = Sensor(id=2, width=1280, height=720)
sensor.reset()
sensor.set_framesize(width=320, height=240) #设置帧大小,默认通道0
sensor.set_pixformat(Sensor.RGB888)  # 设置 RGB888 像素格式 / Set RGB888 pixel format

# -------------------------------
# 初始化显示器(IDE虚拟显示) / Initialize display (IDE virtual output)
# -------------------------------
Display.init(Display.ST7701, width=image_shape[1], height=image_shape[0], to_ide=True, quality=100)

# -------------------------------
# 初始化媒体资源管理器 / Initialize media manager
# -------------------------------
MediaManager.init()
sensor.run()

# -------------------------------
# 启动帧率计时器 / Start FPS timer
# -------------------------------
clock = time.clock()

# -------------------------------
# 霍夫圆检测参数 / Hough Circle parameters
# -------------------------------
dp = 1           # 累加器分辨率与图像分辨率的反比 / Inverse ratio of accumulator resolution
minDist = 30     # 检测到的圆心最小距离 / Minimum distance between detected centers
param1 = 80      # Canny边缘检测高阈值 / Higher threshold for Canny edge detection
param2 = 20      # 霍夫变换圆心检测阈值 / Threshold for center detection in accumulator
minRadius = 10   # 检测圆最小半径 / Minimum circle radius
maxRadius = 50   # 检测圆最大半径 / Maximum circle radius

# -------------------------------
# 主循环 / Main loop
# -------------------------------
while True:
    clock.tick()


    # 拍摄一帧图像 / Capture a frame
    img = sensor.snapshot()
    img_np = img.to_numpy_ref()  # 获取 RGB888 ndarray 引用

    # 调用 cv_lite 扩展的霍夫圆检测函数,返回圆参数列表 [x, y, r, ...]
    circles = cv_lite.rgb888_find_circles(
        frame_shape, img_np, dp, minDist, param1, param2, minRadius, maxRadius
    )
    # 遍历检测到的圆形,绘制圆形框
    for i in range(0, len(circles), 3):
        x = circles[i]
        y = circles[i + 1]
        r = circles[i + 2]
        img.draw_circle(x, y, r, color=(255, 0, 0), thickness=2)  # 红色圆圈
    # 显示带有检测圆的图像 / Display image with circles drawn
    #img_resize = img.copy(roi=(240, 120, 320, 240))
    Display.show_image(img, x=240, y=120)
    # 垃圾回收 / Garbage collect
    gc.collect()

    # 打印帧率 / Print FPS
    print("findcircles:", clock.fps())

# -------------------------------
# 程序退出时释放资源 / Cleanup on exit
# -------------------------------
sensor.stop()
Display.deinit()
os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
time.sleep_ms(100)
MediaManager.deinit()