refactor(fudai): 拆出 _match_icon_template 到 fudai_image_helpers(1400→1273,-127 行)

把 _match_icon_template(135 行)的模板匹配逻辑抽到独立模块:
- _correlation_score:归一化相关系数(去均值后点积/范数乘积)
- _sliding_search_best_score:以模板边长 // 6 为步长滑动搜索
- match_icon_template:等尺寸直接算 / 模板小于 ROI 时先中心裁剪 + 滑动兜底

新增 8 个单元测试(同图完美匹配 / 反相关 / 模板缩放 / threshold 覆盖等)。
1219 → 1227 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-22 03:50:09 +08:00
1 parent f3d4621686
commit e567948ec9
3 files changed
+214 -132

No files matched your search

+4 -131
View File
@@ -693,137 +693,10 @@ class fudai_analyse:
def _match_icon_template(
self, roi_path: str, template_path: str, threshold: float | None = None
) -> Tuple[bool, float]:
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
如果提供 `threshold` 则使用该阈值判断匹配,否则回退到配置 `yanghao_icon_match_threshold`。
返回 (detected, score),若发生错误或文件缺失返回 (False, 0.0)。
"""
try:
if not roi_path or not os.path.exists(roi_path):
return False, 0.0
if not template_path or not os.path.exists(template_path):
return False, 0.0
# use module-level `Image` and `np` imports
roi_img = Image.open(roi_path).convert("RGB")
tpl_img = Image.open(template_path).convert("RGB")
rw, rh = roi_img.size
tw, th = tpl_img.size
# 若模板比 ROI 大,等比缩小模板
if tw > rw or th > rh:
scale = min(rw / tw, rh / th, 1.0)
new_w = max(1, int(tw * scale))
new_h = max(1, int(th * scale))
tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
tw, th = tpl_img.size
# 转为灰度数组
roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32)
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
# 若模板尺寸等于 ROI,则直接计算相关系数
if (
roi_gray.shape[0] == tpl_gray.shape[0]
and roi_gray.shape[1] == tpl_gray.shape[1]
):
A = roi_gray.flatten()
B = tpl_gray.flatten()
else:
# 若模板小于 ROI,则优先取 ROI 中心区域与模板尺寸一致的裁剪进行比对(更稳健),
# 如果中心裁剪分数很低再退回到滑动搜索(成本较高)
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
# 计算中心裁剪窗口
if ih >= th and iw >= tw:
cy = ih // 2 - th // 2
cx = iw // 2 - tw // 2
cy = max(0, min(cy, ih - th))
cx = max(0, min(cx, iw - tw))
window = roi_gray[cy : cy + th, cx : cx + tw]
a = window.flatten()
b = tpl_gray.flatten()
a = a - a.mean()
b = b - b.mean()
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom > 1e-6:
score = float(np.dot(a, b) / denom)
else:
score = -1.0
# 若中心裁剪得分足够好则直接返回
if score >= 0.55:
used_thr = (
float(threshold)
if threshold is not None
else float(
getattr(self, "yanghao_icon_match_threshold", 0.70)
or 0.70
)
)
detected = score >= used_thr
return bool(detected), float(score)
# 退回到滑动搜索(简易版),保留原有步长策略
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
best = -1.0
step_y = max(1, th // 6)
step_x = max(1, tw // 6)
for y in range(0, ih - th + 1, step_y):
for x in range(0, iw - tw + 1, step_x):
window = roi_gray[y : y + th, x : x + tw]
a = window.flatten()
b = tpl_gray.flatten()
a = a - a.mean()
b = b - b.mean()
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom <= 1e-6:
continue
score = float(np.dot(a, b) / denom)
if score > best:
best = score
if best < -0.5:
return False, 0.0
score = float(best)
used_thr = (
float(threshold)
if threshold is not None
else float(
getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70
)
)
detected = score >= used_thr
return bool(detected), float(score)
# 同尺寸直接计算相关系数
A = roi_gray.flatten()
B = tpl_gray.flatten()
A = A - A.mean()
B = B - B.mean()
denom = np.linalg.norm(A) * np.linalg.norm(B)
if denom <= 1e-6:
return False, 0.0
score = float(np.dot(A, B) / denom)
used_thr = (
float(threshold)
if threshold is not None
else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70)
)
detected = score >= used_thr
return bool(detected), float(score)
except Exception:
try:
self._log_kv(
"检测",
"_match_icon_template 异常",
roi_path=roi_path,
template_path=template_path,
)
except Exception:
pass
return False, 0.0
"""对比 ROI 与模板,返回 (detected: bool, score: float)。"""
return fudai_image_helpers.match_icon_template(
self, roi_path, template_path, threshold
)
def _check_in_live_room_by_icon(
self,
@@ -171,3 +171,109 @@ def capture_roi_screenshot(
except Exception:
pass
return ""
def _correlation_score(a_flat, b_flat) -> float:
"""计算两个等长 1D 数组的归一化相关系数(去均值后点积/范数乘积)。"""
import numpy as np
a = a_flat - a_flat.mean()
b = b_flat - b_flat.mean()
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom <= 1e-6:
return -1.0
return float(np.dot(a, b) / denom)
def _sliding_search_best_score(roi_gray, tpl_gray) -> float:
"""以 step ≈ 模板边长 // 6 的步长在 ROI 中滑动搜索最佳相关系数。"""
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
best = -1.0
step_y = max(1, th // 6)
step_x = max(1, tw // 6)
for y in range(0, ih - th + 1, step_y):
for x in range(0, iw - tw + 1, step_x):
window = roi_gray[y : y + th, x : x + tw]
score = _correlation_score(window.flatten(), tpl_gray.flatten())
if score > best:
best = score
return best
def match_icon_template(
analyser: Any,
roi_path: str,
template_path: str,
threshold: Optional[float] = None,
):
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
threshold 不传时使用 analyser.yanghao_icon_match_threshold(默认 0.70)。
出错或文件缺失返回 (False, 0.0)。
"""
import numpy as np
try:
if not roi_path or not os.path.exists(roi_path):
return False, 0.0
if not template_path or not os.path.exists(template_path):
return False, 0.0
roi_img = Image.open(roi_path).convert("RGB")
tpl_img = Image.open(template_path).convert("RGB")
rw, rh = roi_img.size
tw, th = tpl_img.size
if tw > rw or th > rh:
scale = min(rw / tw, rh / th, 1.0)
new_w = max(1, int(tw * scale))
new_h = max(1, int(th * scale))
tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
tw, th = tpl_img.size
roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32)
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
used_thr = (
float(threshold)
if threshold is not None
else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70)
)
# 同尺寸:直接计算
if roi_gray.shape == tpl_gray.shape:
score = _correlation_score(roi_gray.flatten(), tpl_gray.flatten())
return bool(score >= used_thr), float(score)
# 模板小于 ROI:先尝试中心裁剪比对,分数足够好直接返回
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
if ih >= th and iw >= tw:
cy = ih // 2 - th // 2
cx = iw // 2 - tw // 2
cy = max(0, min(cy, ih - th))
cx = max(0, min(cx, iw - tw))
window = roi_gray[cy : cy + th, cx : cx + tw]
score = _correlation_score(window.flatten(), tpl_gray.flatten())
if score >= 0.55:
return bool(score >= used_thr), float(score)
# 退回到滑动搜索
best = _sliding_search_best_score(roi_gray, tpl_gray)
if best < -0.5:
return False, 0.0
return bool(best >= used_thr), float(best)
except Exception:
try:
analyser._log_kv(
"检测",
"_match_icon_template 异常",
roi_path=roi_path,
template_path=template_path,
)
except Exception:
pass
return False, 0.0
+104 -1
View File
@@ -152,7 +152,6 @@ def test_capture_roi_end_to_end_with_real_png(monkeypatch, tmp_path):
a = _make_analyser()
pic_path = tmp_path / "screenshot.png"
# 随机像素让 PNG 大小 > 1024(白色图压缩后过小)
rng = random.Random(42)
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(200 * 200)]
img = Image.new("RGB", (200, 200))
@@ -171,3 +170,107 @@ def test_capture_roi_end_to_end_with_real_png(monkeypatch, tmp_path):
result = fudai_image_helpers.capture_roi_screenshot(a, "test", 100, 100, 50)
assert result
assert "roi_test_test_run" in result
# ---- _correlation_score ---- #
def test_correlation_score_identical_arrays():
import numpy as np
a = np.array([1.0, 2.0, 3.0, 4.0])
score = fudai_image_helpers._correlation_score(a, a)
assert abs(score - 1.0) < 1e-6
def test_correlation_score_constant_arrays_returns_minus_one():
"""相同常数数组 → 范数为 0 → 返回 -1.0"""
import numpy as np
a = np.array([5.0, 5.0, 5.0])
b = np.array([5.0, 5.0, 5.0])
score = fudai_image_helpers._correlation_score(a, b)
assert score == -1.0
def test_correlation_score_anticorrelated():
import numpy as np
a = np.array([1.0, 2.0, 3.0])
b = np.array([3.0, 2.0, 1.0])
score = fudai_image_helpers._correlation_score(a, b)
assert abs(score - (-1.0)) < 1e-6
# ---- match_icon_template ---- #
def test_match_icon_missing_roi_returns_false():
a = _make_analyser()
detected, score = fudai_image_helpers.match_icon_template(
a, "/no/such/roi.png", "/no/such/tpl.png"
)
assert detected is False
assert score == 0.0
def test_match_icon_empty_paths_returns_false():
a = _make_analyser()
assert fudai_image_helpers.match_icon_template(a, "", "x") == (False, 0.0)
assert fudai_image_helpers.match_icon_template(a, "x", "") == (False, 0.0)
def test_match_icon_same_image_high_score(tmp_path):
"""同一张图作为 ROI 与模板 → 完美匹配,score=1.0"""
from PIL import Image
import random
a = _make_analyser()
rng = random.Random(0)
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(60 * 60)]
img = Image.new("RGB", (60, 60))
img.putdata(pixels)
same = tmp_path / "same.png"
img.save(str(same))
detected, score = fudai_image_helpers.match_icon_template(
a, str(same), str(same), threshold=0.5
)
assert detected is True
assert abs(score - 1.0) < 1e-3
def test_match_icon_template_larger_than_roi_gets_resized(tmp_path):
"""模板比 ROI 大 → 自动缩放,仍能比对"""
from PIL import Image
a = _make_analyser()
roi = Image.new("RGB", (50, 50), color="white")
tpl = Image.new("RGB", (200, 200), color="white")
roi_path = tmp_path / "roi.png"
tpl_path = tmp_path / "tpl.png"
roi.save(str(roi_path))
tpl.save(str(tpl_path))
# 不抛错就算通过;都是白色范数为 0,会回到 -1
detected, score = fudai_image_helpers.match_icon_template(
a, str(roi_path), str(tpl_path)
)
# 白色图分母为 0 → score=-1,detected=False
assert detected is False
def test_match_icon_threshold_param_overrides_attr(tmp_path):
"""threshold=0 时即使分数较低也判定为 detected"""
from PIL import Image
import random
a = _make_analyser()
a.yanghao_icon_match_threshold = 0.99 # 默认很高
rng = random.Random(0)
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(40 * 40)]
img = Image.new("RGB", (40, 40))
img.putdata(pixels)
same = tmp_path / "same.png"
img.save(str(same))
# threshold=0 → 任何 score >= 0 都算命中
detected, _ = fudai_image_helpers.match_icon_template(
a, str(same), str(same), threshold=0.0
)
assert detected is True