Files
37duAutomation/libs/desktopauto/desktopauto/matcher.py
T

220 lines
9.3 KiB
Python

# -*- coding: utf-8 -*-
"""模板匹配核心:在一张「屏幕图」里找「模板图」,返回命中位置与相似度。
算法:cv2.matchTemplate(归一化相关系数),支持
- 灰度匹配(默认,快且对细微色差不敏感)或彩色匹配;
- 多尺度(scales):模板与屏幕缩放不一致时(不同 DPI 截的图)仍能命中;
- 多目标:一次返回所有过阈值的位置,重叠框按相似度去重(NMS);
- 透明 PNG:先按白底合成,避免透明区域变黑边导致匹配不上。
"""
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple, Union
import numpy as np
try:
import cv2
except ImportError as _e: # pragma: no cover
raise RuntimeError("缺少依赖 opencv-python,请安装:pip install opencv-python numpy pillow") from _e
DEFAULT_THRESHOLD = 0.85
MIN_TEMPLATE_SIDE = 6 # 模板缩放后最小边长(小于此尺寸不可靠)
MIN_TEMPLATE_STD = 6.0 # 模板灰度标准差低于此值视为「无纹理」(纯色/近似纯色)
logger = logging.getLogger("desktopauto")
@dataclass
class Match:
"""一次命中:匹配框在屏幕上的物理像素位置、尺寸与相似度。"""
left: int
top: int
width: int
height: int
score: float
@property
def center(self) -> Tuple[int, int]:
"""匹配框中心点(点击默认点这里)。"""
return self.left + self.width // 2, self.top + self.height // 2
@property
def region(self) -> Tuple[int, int, int, int]:
"""(left, top, right, bottom)。"""
return self.left, self.top, self.left + self.width, self.top + self.height
def to_dict(self) -> dict:
return {"left": int(self.left), "top": int(self.top),
"width": int(self.width), "height": int(self.height),
"score": round(float(self.score), 4), "center": list(self.center)}
def __str__(self) -> str:
cx, cy = self.center
return (f"Match(({self.left},{self.top}) {self.width}x{self.height} "
f"score={self.score:.3f} center=({cx},{cy}))")
# ==================== 模板加载 ====================
def load_template(template: Union[str, np.ndarray]) -> np.ndarray:
"""加载模板为 BGR 图;带透明通道的 PNG 合成到白底(避免透明区变黑)。"""
if isinstance(template, np.ndarray):
img = template
else:
path = str(template)
if not os.path.isfile(path):
raise RuntimeError(f"模板图不存在:{path}")
data = np.fromfile(path, dtype=np.uint8) # 兼容中文路径
img = cv2.imdecode(data, cv2.IMREAD_UNCHANGED)
if img is None:
raise RuntimeError(f"模板图无法解码(不是有效图片):{path}")
if img.ndim == 2:
return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
if img.shape[2] == 4:
bgr = img[:, :, :3].astype(np.float32)
alpha = (img[:, :, 3:4].astype(np.float32) / 255.0)
return (bgr * alpha + 255.0 * (1.0 - alpha)).astype(np.uint8)
return img[:, :, :3]
def _to_gray(img: np.ndarray) -> np.ndarray:
return img if img.ndim == 2 else cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# ==================== 去重 ====================
def _nms(matches: List[Match], overlap: float = 0.5) -> List[Match]:
"""按分数从高到低保留,丢弃与已保留框重叠(交并比 > overlap)的候选。"""
kept: List[Match] = []
for m in sorted(matches, key=lambda x: x.score, reverse=True):
drop = False
for k in kept:
ix = max(0, min(m.left + m.width, k.left + k.width) - max(m.left, k.left))
iy = max(0, min(m.top + m.height, k.top + k.height) - max(m.top, k.top))
inter = ix * iy
if inter <= 0:
continue
union = m.width * m.height + k.width * k.height - inter
if union > 0 and inter / union > overlap:
drop = True
break
if not drop:
kept.append(m)
return kept
# ==================== 匹配 ====================
def match_in(image: np.ndarray,
template: Union[str, np.ndarray],
threshold: float = DEFAULT_THRESHOLD,
scales: Sequence[float] = (1.0,),
gray: bool = True,
max_results: int = 0,
origin: Tuple[int, int] = (0, 0)) -> List[Match]:
"""在 image 中匹配模板,返回按相似度降序的 Match 列表(坐标已加 origin)。
Args:
image: 屏幕图(BGR 或灰度)。
template: 模板路径或图像。
threshold: 相似度阈值 0~1,越大越严格。
scales: 模板缩放比例集合,如 (0.9, 1.0, 1.1);默认只按原尺寸。
gray: True=灰度匹配(默认),False=彩色匹配。
max_results: 最多返回几条(0=不限)。
origin: image 左上角对应的屏幕坐标(区域/窗口截图时用于换算)。
"""
if image is None or getattr(image, "size", 0) == 0:
raise RuntimeError("屏幕图为空(截图失败)")
tpl_bgr = load_template(template)
screen = _to_gray(image) if gray else image
results: List[Match] = []
tpl_h, tpl_w = tpl_bgr.shape[:2]
scr_h, scr_w = screen.shape[:2]
for scale in (scales or (1.0,)):
try:
scale = float(scale)
except (TypeError, ValueError):
continue
if scale <= 0:
continue
w = max(1, int(round(tpl_w * scale)))
h = max(1, int(round(tpl_h * scale)))
if w < MIN_TEMPLATE_SIDE or h < MIN_TEMPLATE_SIDE:
continue
if w > scr_w or h > scr_h:
continue # 模板比屏幕还大,跳过该尺度
tpl = cv2.resize(tpl_bgr, (w, h), interpolation=cv2.INTER_AREA) if (w, h) != (tpl_w, tpl_h) else tpl_bgr
tpl_use = _to_gray(tpl) if gray else tpl
# 纯色/近似纯色模板:归一化相关系数会把「任何均匀区域」判成高相关(分数不可信),
# 改走平方差匹配(TM_SQDIFF_NORMED,越小越像),再折算成相似度 1-value。
low_texture = float(np.asarray(tpl_use, dtype=np.float32).std()) < MIN_TEMPLATE_STD
method = cv2.TM_SQDIFF_NORMED if low_texture else cv2.TM_CCOEFF_NORMED
try:
res = cv2.matchTemplate(screen, tpl_use, method)
except cv2.error as e: # 极小图/通道不一致等
raise RuntimeError(f"模板匹配失败(模板 {w}x{h},屏幕 {scr_w}x{scr_h}):{e}") from e
if method == cv2.TM_SQDIFF_NORMED:
res = 1.0 - res
logger.debug("模板纹理过低(std<%.1f),改用平方差匹配", MIN_TEMPLATE_STD)
ys, xs = np.where(res >= float(threshold))
if len(xs) == 0:
continue
scores = res[ys, xs]
# 同一尺度内先按分数粗筛,避免超大图产生海量候选
order = np.argsort(-scores)[: max(64, max_results * 4 if max_results else 64)]
for idx in order:
x, y = int(xs[idx]), int(ys[idx])
results.append(Match(
left=x + int(origin[0]), top=y + int(origin[1]),
width=w, height=h, score=float(scores[idx])))
results = _nms(results)
if max_results and max_results > 0:
results = results[:max_results]
return results
def match_any_in(image: np.ndarray,
templates: Sequence[Union[str, np.ndarray]],
threshold: float = DEFAULT_THRESHOLD,
scales: Sequence[float] = (1.0,),
gray: bool = True,
origin: Tuple[int, int] = (0, 0)) -> Tuple[Optional[Match], int]:
"""在一组模板里找「最像的一个」(一个按钮有多种状态时用),返回 (命中, 模板下标)。
都没命中返回 (None, -1);多个模板同时命中时取相似度最高的。
"""
best: Optional[Match] = None
best_idx = -1
for idx, tpl in enumerate(templates or ()):
hits = match_in(image, tpl, threshold=threshold, scales=scales, gray=gray,
max_results=1, origin=origin)
if hits and (best is None or hits[0].score > best.score):
best, best_idx = hits[0], idx
return best, best_idx
def annotate(image: np.ndarray, matches: Sequence[Match],
origin: Tuple[int, int] = (0, 0), color: Tuple[int, int, int] = (0, 200, 0)) -> np.ndarray:
"""把命中框画到图上(调试用),origin 用于把屏幕坐标换回图内坐标。"""
out = image.copy()
ox, oy = int(origin[0]), int(origin[1])
for m in matches:
p1 = (m.left - ox, m.top - oy)
p2 = (p1[0] + m.width, p1[1] + m.height)
cv2.rectangle(out, p1, p2, color, 2)
label = f"{m.score:.3f}"
ty = max(12, p1[1] - 5)
cv2.putText(out, label, (p1[0], ty), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1, cv2.LINE_AA)
return out
def best(matches: Sequence[Match]) -> Optional[Match]:
"""取相似度最高的命中;没有返回 None。"""
return max(matches, key=lambda m: m.score) if matches else None