-
Notifications
You must be signed in to change notification settings - Fork 251
python opencv multi template
qiannian edited this page Jun 13, 2026
·
1 revision
批量加载多个模板,并在指定图片输入源中返回全部命中的模板结果。
import json
from pathlib import Path
from win32com.client import Dispatch
# 创建 op COM 对象
op = Dispatch("op.opsoft")
# 示例图片路径,请提前准备 screen.png、ok.png 和 cancel.png
base_dir = Path(__file__).resolve().parent
source = base_dir / "assets" / "screen.png"
ok = base_dir / "assets" / "ok.png"
cancel = base_dir / "assets" / "cancel.png"
# 不绑定窗口时,通过 SetDisplayInput 指定 OpenCV 匹配的图片输入源
if op.SetDisplayInput(f"pic:{source}") != 1:
raise RuntimeError("设置图片输入源失败")
# 获取图片宽高,后续匹配区域以图片左上角为原点
ret, img_w, img_h = op.GetPicSize(str(source))
if ret != 1:
raise RuntimeError("读取图片尺寸失败")
try:
# 批量加载模板,格式为 name,path|name,path
op.CvLoadTemplateList(f"ok,{ok}|cancel,{cancel}")
# 返回所有命中的模板,结果为 JSON 字符串
ret, info = op.CvMatchAllTemplates(0, 0, img_w, img_h, "ok|cancel", 0.9, 0, 0, 5, 0)
print("匹配结果:", ret)
print(json.dumps(json.loads(info), ensure_ascii=False, indent=2))
finally:
# 清理模板并切回屏幕输入
op.CvRemoveAllTemplates()
op.SetDisplayInput("screen")