# 本作品采用MIT许可协议。
# 版权所有 (c) 2013-2023 OpenMV LLC。保留所有权利。
# https://github.com/openmv/openmv/blob/master/LICENSE
#
# 模板匹配示例 - 归一化互相关(NCC)
#
# 本示例展示了如何使用OpenMV相机的NCC功能将图像块与图像的特定部分进行匹配...
# 但请注意,除非在极其可控的环境中,否则NCC的实用性有限。
#
# 警告: NCC功能需要重新设计! 就目前而言,该功能需要大量改进才能实用。
# 本脚本仅用于展示此功能存在,但当前状态并不完善。
# 导入所需模块
import time # 用于帧率计算
import sensor # 用于相机控制
import image # 用于图像处理
import display
from image import SEARCH_EX # 导入 exhaustive 搜索模式
# 相机初始化
sensor.reset()
# 相机参数设置
sensor.set_contrast(1) # 设置对比度为1
sensor.set_gainceiling(16) # 设置增益上限为16
# 使用NCC进行模板匹配时,SEARCH_EX模式最大支持QQVGA分辨率
sensor.set_framesize(sensor.QQVGA)
# 可通过设置窗口区域来减少搜索范围
# sensor.set_windowing(((640-80)//2, (480-60)//2, 80, 60))
sensor.set_pixformat(sensor.GRAYSCALE) # 使用灰度图以提高匹配准确性
lcd = display.SPIDisplay()
# 加载模板图像
# 模板应为小尺寸灰度图像(如32x32像素)
template = image.Image("/2.pgm")
# 创建时钟对象用于FPS计算
clock = time.clock()
# 主循环:持续进行模板匹配
while True:
clock.tick() # 更新时钟
img = sensor.snapshot() # 捕获当前图像帧
lcd.write(sensor.snapshot())
# 调用find_template方法进行模板匹配
# 参数说明:
# template: 待搜索的模板图像
# threshold: 匹配阈值(0-1),值越高表示匹配越严格
# step: 搜索步长,值越大搜索速度越快但精度可能降低
# search: 搜索算法类型,可选SEARCH_EX(穷举搜索)或SEARCH_DS(菱形搜索)
# roi: 可选参数,指定搜索区域(x, y, w, h)
# 注意:
# 1. ROI必须小于图像且大于模板
# 2. 使用SEARCH_DS时,step和ROI参数会被忽略
r = img.find_template(
template, 0.70, step=4, search=SEARCH_EX
) # 可通过取消注释添加ROI限制: , roi=(10, 0, 60, 60))
# 如果找到匹配区域,则在图像上绘制矩形标记
if r:
img.draw_rectangle(r)
# 打印当前帧率
print(clock.fps())
You are writing to the screen before finding the template. Find the template first and then call lcd.write().