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

135 lines
5.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""离线识图标记:在一张给定的图片上找模板并画框标注(不碰真实屏幕/鼠标)。
用途:
- 模板调优:不用真跑自动化,先拿一张截图验证「能不能找到、找到在哪」;
- 回归测试:固定截图 + 固定模板,验证改版后识别是否还准;
- 上线前预演:标记图上的框中心 = 真实点击会落下的位置,先看一眼再开跑。
与 Screen 的区别:Screen 走实时截屏 + 真实点击;本模块纯离屏计算,输出一张标注图。
"""
from __future__ import annotations
import os
from typing import Dict, List, Optional, Sequence, 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
from . import capture, matcher as _m
from .matcher import Match
# 多个模板依次使用的框颜色(BGR)
_COLORS = [
(0, 200, 0), # 绿
(255, 140, 0), # 蓝
(0, 128, 255), # 橙
(200, 0, 200), # 紫
(0, 220, 220), # 黄
]
Template = Union[str, np.ndarray]
def _label_text(index: int, score: float) -> str:
"""框上标注:序号 + 相似度。只用 ASCII,避免 cv2.putText 画中文变问号。"""
return f"#{index} {score:.3f}"
def mark(image: Union[str, np.ndarray],
templates: Sequence[Template],
out_path: str = "",
threshold: float = _m.DEFAULT_THRESHOLD,
scales: Sequence[float] = (1.0,),
gray: bool = True,
draw_click_point: bool = True) -> Dict[str, object]:
"""在大图里找多个模板并画框标记,返回结果 dict(不修改原图,除输出文件外无副作用)。
Args:
image: 大图(路径或 BGR ndarray)。
templates: 模板列表(路径或 ndarray),同一模板的命中用同一种颜色。
out_path: 标注图输出路径;留空则不落盘,只返回内存图(见返回的 image)。
threshold: 相似度阈值。
scales: 模板缩放集合(跨分辨率时用,如 (0.9, 1.0, 1.1))。
gray: 灰度匹配(默认 True)。
draw_click_point: 是否在框中心画十字(代表真实点击会落的位置)。
Returns:
{
"out": 标注图路径(未落盘时为空串),
"image": 标注后的 BGR ndarray,
"size": {"width": w, "height": h},
"items": [{"index": 1, "template": 文件名, "count": n, "matches": [{...}, ...]}],
"total": 命中总数,
}
"""
if isinstance(image, np.ndarray):
base = image.copy()
else:
path = str(image)
if not os.path.isfile(path):
raise RuntimeError(f"待识别的图片不存在:{path}")
base = _m.load_template(path) # 复用「兼容中文路径 + 透明合成」的读取逻辑
if isinstance(templates, (str, np.ndarray)):
templates = [templates]
if not templates:
raise RuntimeError("至少需要一个模板图")
items: List[dict] = []
total = 0
for idx, tpl in enumerate(templates, start=1):
matches = _m.match_in(base, tpl, threshold=threshold, scales=scales, gray=gray)
total += len(matches)
items.append({
"index": idx,
"template": os.path.basename(str(tpl)) if isinstance(tpl, str) else f"ndarray_{idx}",
"count": len(matches),
"matches": [m.to_dict() for m in matches],
})
_draw(base, matches, idx, _COLORS[(idx - 1) % len(_COLORS)], draw_click_point)
out = ""
if out_path:
out = capture.save_image(base, out_path)
return {
"out": out,
"image": base,
"size": {"width": int(base.shape[1]), "height": int(base.shape[0])},
"items": items,
"total": total,
}
def _draw(img: np.ndarray, matches: Sequence[Match], index: int,
color: tuple, draw_click_point: bool) -> None:
"""在图上画命中框 + 标签 + 中心十字(原地修改)。"""
for m in matches:
p1 = (int(m.left), int(m.top))
p2 = (int(m.left + m.width), int(m.top + m.height))
cv2.rectangle(img, p1, p2, color, 2)
text = _label_text(index, m.score)
ty = p1[1] - 6 if p1[1] >= 14 else p2[1] + 14
cv2.putText(img, text, (p1[0], ty), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1, cv2.LINE_AA)
if draw_click_point:
cx, cy = m.center
cv2.drawMarker(img, (int(cx), int(cy)), color, cv2.MARKER_CROSS, 12, 1)
def summarize(result: Dict[str, object]) -> str:
"""把 mark() 的结果拼成一段可读文本(日志/CLI 输出用)。"""
lines = [f"图片尺寸:{result['size']['width']}x{result['size']['height']},命中合计 {result['total']} 处"]
for item in result["items"]: # type: ignore[union-attr]
lines.append(f" #{item['index']} {item['template']}:{item['count']} 处")
for m in item["matches"]:
lines.append(f" score={m['score']:.3f} 框=({m['left']},{m['top']}) "
f"{m['width']}x{m['height']} 点击点={tuple(m['center'])}")
if result.get("out"):
lines.append(f"标注图:{result['out']}")
return "\n".join(lines)