208 lines
9.0 KiB
Python
208 lines
9.0 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""找色与界面差异:不需要模板图的「轻量识图」。
|
||
|
||
典型用途:
|
||
- find_color:找状态点(红/绿圆点)、高亮行、进度条颜色,判断「有没有变红/变绿」;
|
||
- diff:比对两次截图,判断界面有没有变化(比找具体元素更鲁棒,也能判断卡死/无响应)。
|
||
|
||
颜色约定:对外一律用 RGB(`"#FF3B30"` / `(255, 59, 48)` / `"255,59,48"`),内部转 BGR。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
from typing import Dict, 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
|
||
|
||
from . import capture
|
||
|
||
RGB = Tuple[int, int, int]
|
||
|
||
|
||
@dataclass
|
||
class ColorMatch:
|
||
"""一块同色区域(连通域)的位置与面积。"""
|
||
|
||
left: int
|
||
top: int
|
||
width: int
|
||
height: int
|
||
area: int
|
||
color: RGB
|
||
|
||
@property
|
||
def center(self) -> Tuple[int, int]:
|
||
return self.left + self.width // 2, self.top + self.height // 2
|
||
|
||
def to_dict(self) -> dict:
|
||
return {"left": int(self.left), "top": int(self.top),
|
||
"width": int(self.width), "height": int(self.height),
|
||
"area": int(self.area), "color": list(self.color),
|
||
"center": list(self.center)}
|
||
|
||
def __str__(self) -> str:
|
||
cx, cy = self.center
|
||
return (f"ColorMatch({self.color} ({self.left},{self.top}) {self.width}x{self.height} "
|
||
f"area={self.area} center=({cx},{cy}))")
|
||
|
||
|
||
# ==================== 颜色解析 ====================
|
||
def parse_color(color: Union[str, Sequence[int]]) -> RGB:
|
||
"""解析颜色为 (r, g, b);支持 "#RRGGBB"、"#RGB"、"(r,g,b)"、"r,g,b"。"""
|
||
if isinstance(color, str):
|
||
s = color.strip().lstrip("#")
|
||
if "," in s:
|
||
parts = [p.strip() for p in s.split(",")]
|
||
else:
|
||
if len(s) == 3:
|
||
s = "".join(ch * 2 for ch in s)
|
||
if len(s) != 6:
|
||
raise ValueError(f"颜色格式不正确:{color}(支持 #RRGGBB 或 r,g,b)")
|
||
parts = [s[0:2], s[2:4], s[4:6]]
|
||
try:
|
||
return tuple(int(p, 16) for p in parts) # type: ignore[return-value]
|
||
except ValueError as e:
|
||
raise ValueError(f"颜色格式不正确:{color}") from e
|
||
values = []
|
||
for p in parts:
|
||
try:
|
||
v = int(float(p))
|
||
except ValueError as e:
|
||
raise ValueError(f"颜色格式不正确:{color}") from e
|
||
values.append(max(0, min(255, v)))
|
||
if len(values) != 3:
|
||
raise ValueError(f"颜色需要 3 个分量:{color}")
|
||
return values[0], values[1], values[2] # type: ignore[return-value]
|
||
if isinstance(color, (tuple, list)) and len(color) == 3:
|
||
return tuple(max(0, min(255, int(v))) for v in color) # type: ignore[return-value]
|
||
raise ValueError(f"颜色格式不正确:{color}")
|
||
|
||
|
||
def _rgb_to_bgr(rgb: RGB) -> Tuple[int, int, int]:
|
||
return int(rgb[2]), int(rgb[1]), int(rgb[0])
|
||
|
||
|
||
# ==================== 找色 ====================
|
||
def find_color_in(image: np.ndarray, color: Union[str, Sequence[int]],
|
||
tolerance: int = 12, min_area: int = 4,
|
||
max_results: int = 0, origin: Tuple[int, int] = (0, 0)) -> List[ColorMatch]:
|
||
"""在一张图里找指定颜色(及容差范围内)的连通区域。"""
|
||
rgb = parse_color(color)
|
||
b, g, r = _rgb_to_bgr(rgb)
|
||
tol = max(0, int(tolerance))
|
||
lower = np.array([max(0, b - tol), max(0, g - tol), max(0, r - tol)], dtype=np.uint8)
|
||
upper = np.array([min(255, b + tol), min(255, g + tol), min(255, r + tol)], dtype=np.uint8)
|
||
mask = cv2.inRange(image, lower, upper)
|
||
count, _labels, stats, _centroids = cv2.connectedComponentsWithStats(mask, connectivity=8)
|
||
out: List[ColorMatch] = []
|
||
for i in range(1, count): # 0 = 背景
|
||
x, y, w, h, area = (int(v) for v in stats[i][:5])
|
||
if area < max(0, int(min_area)):
|
||
continue
|
||
out.append(ColorMatch(left=x + int(origin[0]), top=y + int(origin[1]),
|
||
width=w, height=h, area=area, color=rgb))
|
||
out.sort(key=lambda c: c.area, reverse=True)
|
||
if max_results and max_results > 0:
|
||
out = out[:max_results]
|
||
return out
|
||
|
||
|
||
def find_color(color: Union[str, Sequence[int]], tolerance: int = 12,
|
||
region: Optional[Sequence[int]] = None,
|
||
window: Union[int, str, None] = None,
|
||
min_area: int = 4, max_results: int = 0) -> List[ColorMatch]:
|
||
"""实时截图找色,返回区域列表(坐标已换算成屏幕坐标,按面积降序)。"""
|
||
img, reg = capture.grab(region=region, window=window)
|
||
return find_color_in(img, color, tolerance=tolerance, min_area=min_area,
|
||
max_results=max_results, origin=(reg[0], reg[1]))
|
||
|
||
|
||
def find_colors(colors: Sequence[Union[str, Sequence[int]]], tolerance: int = 12,
|
||
region: Optional[Sequence[int]] = None,
|
||
window: Union[int, str, None] = None,
|
||
min_area: int = 4, max_results: int = 0) -> Dict[str, List[ColorMatch]]:
|
||
"""一次截图、找多种颜色(避免多次截屏),返回 {颜色文本: [ColorMatch...]}。"""
|
||
img, reg = capture.grab(region=region, window=window)
|
||
out: Dict[str, List[ColorMatch]] = {}
|
||
for c in colors:
|
||
rgb = parse_color(c)
|
||
out[str(c)] = find_color_in(img, rgb, tolerance=tolerance, min_area=min_area,
|
||
max_results=max_results, origin=(reg[0], reg[1]))
|
||
return out
|
||
|
||
|
||
# ==================== 界面差异 ====================
|
||
def _load(image: Union[str, np.ndarray]) -> np.ndarray:
|
||
if isinstance(image, np.ndarray):
|
||
return image
|
||
from .matcher import load_template # 复用「兼容中文路径」的读取
|
||
return load_template(str(image))
|
||
|
||
|
||
def diff(a: Union[str, np.ndarray], b: Optional[Union[str, np.ndarray]] = None,
|
||
tolerance: int = 10, min_area: int = 30,
|
||
region: Optional[Sequence[int]] = None,
|
||
window: Union[int, str, None] = None) -> dict:
|
||
"""比对两张图(或「给定图 vs 当前截图」),返回变化比例与变化区域。
|
||
|
||
Args:
|
||
a: 基准图(路径或 ndarray)。
|
||
b: 对比图;None 时现场按 region/window 截一帧(要求与 a 同尺寸)。
|
||
tolerance: 像素差阈值(0~255),越大越宽松。
|
||
min_area: 变化区域最小面积(过滤噪点/光标闪烁)。
|
||
region / window: b 为 None 时的截图范围。
|
||
|
||
Returns:
|
||
{"changed": bool, "changed_ratio": float, "boxes": [{"left","top","width","height","center"}],
|
||
"image": 差异可视化 ndarray(变化区域画红框)}
|
||
"""
|
||
img_a = _load(a)
|
||
if b is None:
|
||
img_b, reg = capture.grab(region=region, window=window)
|
||
ox, oy = int(reg[0]), int(reg[1])
|
||
else:
|
||
img_b = _load(b)
|
||
ox, oy = 0, 0
|
||
|
||
if img_a.shape[:2] != img_b.shape[:2]:
|
||
img_b = cv2.resize(img_b, (img_a.shape[1], img_a.shape[0]), interpolation=cv2.INTER_AREA)
|
||
|
||
gray_a = cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY) if img_a.ndim == 3 else img_a
|
||
gray_b = cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY) if img_b.ndim == 3 else img_b
|
||
delta = cv2.absdiff(gray_a, gray_b)
|
||
_thr, mask = cv2.threshold(delta, max(0, int(tolerance)), 255, cv2.THRESH_BINARY)
|
||
changed_px = int(np.count_nonzero(mask))
|
||
total_px = int(mask.shape[0] * mask.shape[1]) or 1
|
||
|
||
boxes: List[dict] = []
|
||
count, _labels, stats, _c = cv2.connectedComponentsWithStats(mask, connectivity=8)
|
||
for i in range(1, count):
|
||
x, y, w, h, area = (int(v) for v in stats[i][:5])
|
||
if area < max(0, int(min_area)):
|
||
continue
|
||
boxes.append({"left": x + ox, "top": y + oy, "width": w, "height": h,
|
||
"center": [x + ox + w // 2, y + oy + h // 2]})
|
||
boxes.sort(key=lambda bx: (bx["top"], bx["left"]))
|
||
|
||
vis = img_b.copy() if img_b.ndim == 3 else cv2.cvtColor(img_b, cv2.COLOR_GRAY2BGR)
|
||
for bx in boxes:
|
||
cv2.rectangle(vis, (bx["left"] - ox, bx["top"] - oy),
|
||
(bx["left"] - ox + bx["width"], bx["top"] - oy + bx["height"]), (0, 0, 255), 2)
|
||
|
||
return {"changed": bool(boxes) or changed_px > 0,
|
||
"changed_ratio": round(changed_px / total_px, 4),
|
||
"boxes": boxes, "image": vis}
|
||
|
||
|
||
def diff_ratio(a: Union[str, np.ndarray], b: Optional[Union[str, np.ndarray]] = None,
|
||
tolerance: int = 10, region: Optional[Sequence[int]] = None,
|
||
window: Union[int, str, None] = None) -> float:
|
||
"""只要变化比例(0~1)时用这个,比 diff() 轻。"""
|
||
return float(diff(a, b, tolerance=tolerance, min_area=1,
|
||
region=region, window=window)["changed_ratio"])
|