复制代码如下:
import time
import os
import sys
from media.sensor import *
from media.display import *
from media.media import *
from time import ticks_ms
sensor = None
自定义函数
try:
# 初始化摄像头,分辨率确保为8的倍数(避免尺寸错误)
sensor = Sensor(width=480, height=320)
sensor.reset()
sensor.set_framesize(width=480, height=320)
sensor.set_pixformat(Sensor.RGB565)
# 初始化显示(虚拟显示模式,适配电脑IDE查看)
Display.init(Display.LT9611, to_ide=True)
MediaManager.init()
sensor.run()
clock = time.clock()
while True:
clock.tick()
os.exitpoint()
img = sensor.snapshot(chn=CAM_CHN_ID_0)
# 预处理:转为灰度图并二值化
img_rect = img.to_grayscale(copy=True)
img_rect = img_rect.binary([(0, 75)])
# 查找所有矩形
rects = img_rect.find_rects(threshold=10000)
# 初始化参数
max_area = 0
max_corners = None
第一步:锁定A4纸边框
# 遍历所有矩形,筛选最大面积矩形
if rects: # 确保找到矩形再处理
for rect in rects:
corners = rect.corners() # 获取矩形四个角点坐标 [(x0,y0), (x1,y1), (x2,y2), (x3,y3)]
# 转换8个坐标值为int型
int_corners = [(int(c[0]), int(c[1])) for c in corners]
# 计算矩形宽高(基于角点坐标,适用于轴对齐矩形)
# 宽:x方向差值(corner[1]-corner[0])
width = abs(corners[1][0] - corners[0][0])
# 高:y方向差值(corner[3]-corner[0])
height = abs(corners[3][1] - corners[0][1])
# 计算面积(避免负数,取绝对值)
area = width * height
# 更新最大矩形信息
if area > max_area:
max_area = area
max_corners = corners # 保存最大矩形的角点
# 绘制最大矩形(用红线突出显示)
if max_corners:
# 锁定最大矩形边框
img.draw_line(max_corners[0][0], max_corners[0][1], max_corners[1][0], max_corners[1][1], color=(255, 0, 0), thickness=2)
img.draw_line(max_corners[1][0], max_corners[1][1], max_corners[2][0], max_corners[2][1], color=(255, 0, 0), thickness=2)
img.draw_line(max_corners[2][0], max_corners[2][1], max_corners[3][0], max_corners[3][1], color=(255, 0, 0), thickness=2)
img.draw_line(max_corners[3][0], max_corners[3][1], max_corners[0][0], max_corners[0][1], color=(255, 0, 0), thickness=2)
第二步:flood-fill算法填充排除外界干扰
img.flood_fill(x = max_corners[0][0]-5,y = max_corners[0][1]-5,color = (255,255,255))
# 显示帧率
img.draw_string_advanced(10, 10, 20, "fps: {}".format(int(clock.fps())), color=(255, 0, 0))
# 传输到IDE显示
img.compressed_for_ide()
Display.show_image(img)
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()
期待结果和实际结果
希望正常运行,实际有时候能运行有时候不行
软硬件版本信息
硬件为k230庐山派,ide版本为4.0.7-0,固件版本0.4.0
错误日志
报错如下:
MPY: soft reboot
CanMV v1.3-90-gcf5bdef(based on Micropython e00a144) on 2025-07-26; k230_canmv_lckfb with K230
find sensor gc2093_csi2, type 25, output 1280x960@90
vb common pool count 4
sensor(0), mode 0, buffer_num 4, buffer_size 0
异常: function missing 1 required positional arguments
MPY: soft reboot
CanMV v1.3-90-gcf5bdef(based on Micropython e00a144) on 2025-07-26; k230_canmv_lckfb with K230
尝试解决过程
补充材料