-
Notifications
You must be signed in to change notification settings - Fork 251
python opencv template match
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 和 button.png
base_dir = Path(__file__).resolve().parent
source = base_dir / "assets" / "screen.png"
template = base_dir / "assets" / "button.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:
# 加载模板
op.CvLoadTemplate("button", str(template))
# 在整张输入图片范围内匹配模板
ret, info = op.CvMatchTemplate(0, 0, img_w, img_h, "button", 0.9, 0, 0, 5, 0)
print("匹配结果:", ret)
print(json.dumps(json.loads(info), ensure_ascii=False, indent=2))
finally:
# 清理模板并切回屏幕输入
op.CvRemoveTemplate("button")
op.SetDisplayInput("screen")