• 方案介绍
  • 附件下载
  • 相关推荐
申请入驻 产业图谱

3.5.2-4-先识别框 框内数字识别 数字模板匹配 openmv K210 k230

04/11 08:28
520
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

联系方式.txt

共1个文件

[相关器件] CSD97370Q5M

开关稳压器/控制器,CSD97370Q5M 30 V 25 A SON 5 x 6 mm synchronous buck NexFET power stage

**非常详细的视频和文字教程,讲解常见的openmv教程包括 巡线、物体识别、圆环识别、阈值自动获取等。非常适合学习openmv、K210、K230等项目
视频合集链接在


openmv教程合集 openmv入门到项目开发 openmv和STM32通信 openmv和opencv区别 openmv巡线 openmv数字识别教程LCD

专刊openmv视觉文章链接:
https://blog.csdn.net/qq_46187594/category_12900902.html

一种常见的识别算法优化方法,先根据物体特征缩小识别范围,在特征的范围内进行某种识别算法,比如根据数字是黑色方框框起来的特征,先识别黑色框,然后框内进行匹配。

我们使用3.5.2中的2的进行优化,优化方式是 先让openmv识别框,然后框内进行数字模板匹配
在这里插入图片描述
效果还可以帧率20左右,可以识别到的框然后进行数字识别的,偶尔会识别不到两个数字,可能只能识别一个数字

下面这个代码帧率20,可以同时识别两个数字,

# 多模板匹配系统 
import time
import sensor
import image

# ******************** 硬件初始化配置 ********************
sensor.reset()                      # 复位摄像头硬件
sensor.set_contrast(1)             # 设置对比度(范围0-3)
sensor.set_gainceiling(16)         # 设置最大增益值(2^16)
sensor.set_framesize(sensor.QQVGA) # 设置分辨率160x120(低分辨率提升处理速度)
sensor.set_pixformat(sensor.GRAYSCALE)  # 灰度图像模式(减少计算量)
sensor.set_vflip(True)             # 垂直翻转图像(适配摄像头安装方向)
sensor.set_hmirror(True)           # 水平镜像图像(解决镜头镜像问题)

# ******************** 用户可调参数 ********************
TEMPLATE_PATHS = [                 # 模板文件路径列表(按0-9顺序)
    "/0.pgm", "/1.pgm", "/2.pgm",
    "/3.pgm", "/4.pgm", "/5.pgm",
    "/6.pgm", "/7.pgm", "/8.pgm",
    "/9.pgm"
]
MATCH_THRESHOLD = 0.65           # 模板匹配相似度阈值(0.0-1.0)
RECT_THRESHOLD = 25000           # 矩形检测敏感度(值越小敏感度越高)
MIN_RECT_WIDTH = 15              # 最小矩形宽度(需大于最大模板宽度)
MIN_RECT_HEIGHT = 15             # 最小矩形高度(需大于最大模板高度)
TEXT_COLOR = 255                 # 显示颜色(灰度值,255为白色)
TEXT_OFFSET = 5                  # 文本标注偏移量(像素)

# ******************** 模板管理系统 ********************
class TemplateLoader:
    def __init__(self):
        self.templates = []       # 存储加载的模板信息
        self.min_template_w = 999 # 记录最小模板宽度(用于尺寸校验)
        self.min_template_h = 999 # 记录最小模板高度
        self.load_templates()     # 初始化时自动加载模板

    def load_templates(self):
        """模板加载与管理系统
        功能:批量加载模板文件并记录尺寸信息
        安全机制:异常捕获+详细加载报告"""
        print("n====== 模板加载报告 ======")
        for path in TEMPLATE_PATHS:
            try:
                # 加载模板图像并提取尺寸信息
                template_img = image.Image(path)
                w, h = template_img.width(), template_img.height()
                
                # 更新最小模板尺寸记录
                self.min_template_w = min(self.min_template_w, w)
                self.min_template_h = min(self.min_template_h, h)
                
                # 存储模板元数据
                self.templates.append({
                    "image": template_img,    # 模板图像对象
                    "name": path.split("/")[-1].split(".")[0],  # 提取数字名称
                    "path": path,             # 完整文件路径
                    "width": w,               # 模板宽度
                    "height": h               # 模板高度
                })
                print(f"成功加载 {w}x{h} 模板: {path}")
            except Exception as e:
                print(f"加载失败: {path} ({str(e)})")
        print("=========================n")

# ******************** 主程序流程 ********************
template_loader = TemplateLoader()  # 实例化模板加载器
clock = time.clock()                # 创建帧率计算器

while True:
    clock.tick()  # 开始帧计时
    # 图像采集与预处理
    img = sensor.snapshot().lens_corr(strength=1.8)  # 捕获图像并校正镜头畸变
    
    # 阶段1:矩形检测与预处理
    rects = img.find_rects(threshold=RECT_THRESHOLD)  # 查找所有矩形区域
    
    for rect in rects:
        x, y, w, h = rect.rect()  # 提取矩形坐标和尺寸
        
        # 区域过滤(尺寸+面积双重校验)
        if (w < MIN_RECT_WIDTH or h < MIN_RECT_HEIGHT or
            w * h < MIN_RECT_WIDTH * MIN_RECT_HEIGHT):
            continue  # 跳过过小区域
        
        # ROI安全边界处理(防止越界访问)
        img_w, img_h = img.width(), img.height()
        roi_x = max(0, x)              # 左边界保护
        roi_y = max(0, y)              # 上边界保护
        roi_w = min(w, img_w - roi_x)  # 宽度边界保护
        roi_h = min(h, img_h - roi_y)  # 高度边界保护

        # 绘制矩形标记(轮廓+角点)
        img.draw_rectangle(x, y, w, h, color=TEXT_COLOR)  # 绘制矩形框
        for (cx, cy) in rect.corners():  # 绘制四个角点
            img.draw_circle(int(cx), int(cy), 3, color=TEXT_COLOR)
        
        # 阶段2:模板匹配 - 找出相似度最高的模板
        best_match = None       # 存储最佳匹配结果
        best_similarity = 0.0   # 最高相似度记录
        best_name = None        # 对应模板名称
        
        for template in template_loader.templates:
            # 动态尺寸校验(ROI必须大于等于模板尺寸)
            if roi_w < template["width"] or roi_h < template["height"]:
                continue  # 跳过尺寸不匹配的模板
            
            try:
                # 执行模板匹配(核心算法)
                result = img.find_template(
                    template["image"],      # 模板图像
                    MATCH_THRESHOLD,        # 相似度阈值
                    roi=(roi_x, roi_y, roi_w, roi_h)  # 搜索区域
                )
                
                # 结果处理
                if result:
                    rx, ry, rw, rh = result  # 解包匹配结果坐标
                    similarity = MATCH_THRESHOLD  # 使用阈值作为相似度基准值
                    if similarity > best_similarity:
                        best_similarity = similarity
                        best_match = (rx, ry, rw, rh)
                        best_name = template["name"]
            
            except Exception as e:
                print(f"模板匹配出错: {str(e)}")  # 异常捕获

        # 结果可视化与输出
        if best_match:
            rx, ry, rw, rh = best_match
            # 绘制匹配区域框
            img.draw_rectangle(rx, ry, rw, rh, color=TEXT_COLOR)
            # 计算文本位置(防越界)
            text_y = ry - TEXT_OFFSET if ry > TEXT_OFFSET else 0
            # 绘制识别结果文本
            img.draw_string(rx, text_y, best_name,
                            color=TEXT_COLOR,
                            scale=1,        # 字体大小
                            mono_space=True # 等宽字体
                           )
            
            # 增强数据输出(带时间戳和坐标信息)
            print("[{:.0f}] 区域[{},{} {}x{}] 识别到{} 相似度{:.2f} 位置({},{})".format(
                time.ticks_ms(),        # 时间戳
                x, y, w, h,             # 原始区域信息
                best_name,              # 识别结果
                best_similarity,        # 匹配度
                rx + rw // 2,           # 中心X坐标
                ry + rh // 2            # 中心Y坐标
            ))

    # 性能显示(右上角FPS计数器)
    img.draw_string(5, 5, "FPS:%.1f" % clock.fps(), color=TEXT_COLOR)
  • 联系方式.txt
    下载
[相关器件] CSD97370Q5M

开关稳压器/控制器,CSD97370Q5M 30 V 25 A SON 5 x 6 mm synchronous buck NexFET power stage

点赞
收藏
评论
分享
加入交流群
举报

相关推荐

方案定制

去合作
方案开发定制化,2000+方案商即时响应!