From a391c21f47e21f91b00bcb03ffa97fb02795409e Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 22 May 2026 04:55:08 +0800 Subject: [PATCH] =?UTF-8?q?refactor(detection):=20=E6=8B=86=E5=87=BA=20fin?= =?UTF-8?q?der.py=20=E6=A8=A1=E6=9D=BF=E5=8C=B9=E9=85=8D=E5=85=9C=E5=BA=95?= =?UTF-8?q?=EF=BC=88936=E2=86=92719=EF=BC=8C-217=20=E8=A1=8C=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"块(226 行)抽到 template_match_helpers.template_match_fallback: - 模板加载与缩放 - 搜索区域裁剪 + 边界保护 - cv2.matchTemplate + 双阈值判定 - 调试截图保存(last_match.png + 双截图记录) 新增 5 个单元测试覆盖:模板缺失 / 模板读取失败 / 阈值异常 / 不可达阈值 / 完美匹配。 1315 → 1320 用例全过。 Co-Authored-By: Claude Opus 4.7 (1M context) --- douyin/detection/detection_pkg/finder.py | 231 +--------------- .../detection_pkg/template_match_helpers.py | 247 ++++++++++++++++++ tests/test_template_match_helpers.py | 139 ++++++++++ 3 files changed, 393 insertions(+), 224 deletions(-) create mode 100644 douyin/detection/detection_pkg/template_match_helpers.py create mode 100644 tests/test_template_match_helpers.py diff --git a/douyin/detection/detection_pkg/finder.py b/douyin/detection/detection_pkg/finder.py index e7b506f..7c2f9c9 100644 --- a/douyin/detection/detection_pkg/finder.py +++ b/douyin/detection/detection_pkg/finder.py @@ -14,6 +14,7 @@ from typing import Any from PIL import Image from ._common import _ensure_detection_cache +from .template_match_helpers import template_match_fallback def check_have_fudai_with_ready_screenshot( @@ -582,230 +583,12 @@ def check_have_fudai_with_ready_screenshot( # 像素检测未命中时,使用模板匹配作为兜底 if not detected or detected_x is None: - try: - import cv2 - import numpy as np - - # 获取模板路径 - try: - from douyin.core import path_config - - template_path = path_config.get_assets_dir() + "/fudai.png" - except Exception: - # 回退到旧路径(向后兼容) - base_dir = os.path.dirname(__file__) - template_path = os.path.join(base_dir, "assets", "fudai.png") - - if os.path.exists(template_path): - # 获取匹配阈值 - try: - template_threshold = float( - getattr(analyser, "fudai_template_match_threshold", 0.7) - or 0.7 - ) - except Exception: - template_threshold = 0.7 - - # 读取模板 - template = cv2.imread(template_path, cv2.IMREAD_COLOR) - if template is not None: - # 将PIL图片转换为OpenCV格式 - pic_rgb = pic_new.convert("RGB") - screenshot_bgr = cv2.cvtColor( - np.array(pic_rgb), cv2.COLOR_RGB2BGR - ) - - # 定义搜索区域:X=156-269(1080基准),Y=351-451(2400基准) - x1 = max(0, 156 * rx // 1080) - x2 = min(width, 269 * rx // 1080) - y_top = max(0, 351 * ry // 2400 + y_pianyi_val) - y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val) - - if x1 < x2 and y_top < y_bottom: - search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index] - - if search_roi.size > 0: - th, tw = template.shape[:2] - rh, rw = search_roi.shape[:2] - - # 保存搜索区域截图到 last_match.png - try: - base_dir = os.path.dirname(__file__) - pic_base = os.path.join(base_dir, "pic") - match_dir = os.path.join(pic_base, "template_match") - os.makedirs(match_dir, exist_ok=True) - last_match_path = os.path.join( - match_dir, "last_match.png" - ) - - # 保存截图并检查是否成功 - save_success = cv2.imwrite( - last_match_path, search_roi - ) - if save_success: - try: - analyser._log_kv( - "[找福袋图标] 已保存搜索区域截图", - loop=loop, - 文件路径=last_match_path, - 搜索区域尺寸=f"{rw}x{rh}", - 搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "[找福袋图标] 保存搜索区域截图失败", - loop=loop, - 文件路径=last_match_path, - ) - except Exception: - pass - except Exception as save_err: - try: - analyser._log_kv( - "[找福袋图标] 保存搜索区域截图异常", - loop=loop, - 错误类型=type(save_err).__name__, - 错误信息=str(save_err), - ) - except Exception: - pass - - # 如果模板太大,缩小模板 - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - if scale > 0: - template = cv2.resize( - template, - ( - max(1, int(tw * scale)), - max(1, int(th * scale)), - ), - ) - th, tw = template.shape[:2] - - # 执行模板匹配 - if th <= rh and tw <= rw: - res = cv2.matchTemplate( - search_roi, template, cv2.TM_CCOEFF_NORMED - ) - _min_val, max_val, _min_loc, max_loc = ( - cv2.minMaxLoc(res) - ) - - # 双截图记录:保存实时操作截图(搜索区域) - try: - from douyin.handlers import douyin_screenshot_manager - from PIL import Image as PILImage - - search_roi_pil = PILImage.fromarray( - cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB) - ) - douyin_screenshot_manager.save_latest_attempt( - search_roi_pil, - operation_type="template_match", - ) - except Exception: - pass - - try: - analyser._log_kv( - "[找福袋图标] 模板匹配兜底", - loop=loop, - 匹配分数=round(max_val, 4), - 阈值=template_threshold, - 是否通过=bool( - max_val >= template_threshold - ), - 搜索区域=f"({x1},{y_top})-({x2},{y_bottom})", - 搜索区域尺寸=f"{rw}x{rh}", - 模板尺寸=f"{tw}x{th}", - 截图尺寸=f"{width}x{height}", - 分辨率=f"{rx}x{ry}", - ) - except Exception: - pass - - if max_val >= template_threshold: - # 双截图记录:保存成功识别存档截图 - try: - from douyin.handlers import douyin_screenshot_manager - from PIL import Image as PILImage - - search_roi_pil = PILImage.fromarray( - cv2.cvtColor( - search_roi, cv2.COLOR_BGR2RGB - ) - ) - douyin_screenshot_manager.save_last_success( - search_roi_pil, - operation_type="template_match", - ) - except Exception: - pass - # 计算检测到的X坐标(1080基准) - detected_x_in_roi = max_loc[0] - detected_x = int( - (x1 + detected_x_in_roi + tw // 2) - * 1080.0 - / max(1, rx) - ) - detected = True - try: - analyser.last_find_fudai_time = time.time() - except Exception: - pass - else: - # 模板尺寸不匹配,记录调试信息 - try: - analyser._log_kv( - "[找福袋图标] 模板匹配失败-尺寸不匹配", - loop=loop, - 模板尺寸=f"{tw}x{th}", - 搜索区域尺寸=f"{rw}x{rh}", - 条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})", - ) - except Exception: - pass - else: - # 搜索区域为空,记录调试信息 - try: - analyser._log_kv( - "[找福袋图标] 模板匹配失败-搜索区域为空", - loop=loop, - 搜索区域=f"({x1},{y_top})-({x2},{y_bottom})", - 截图尺寸=f"{width}x{height}", - ) - except Exception: - pass - else: - # 搜索区域坐标无效,记录调试信息 - try: - analyser._log_kv( - "[找福袋图标] 模板匹配失败-坐标无效", - loop=loop, - x1=x1, - x2=x2, - y_top=y_top, - y_bottom=y_bottom, - 截图尺寸=f"{width}x{height}", - 分辨率=f"{rx}x{ry}", - ) - except Exception: - pass - except (ImportError, Exception) as e: - # OpenCV不可用或模板匹配失败,继续使用像素检测结果 - try: - analyser._log_kv( - "[找福袋图标] 模板匹配异常", - loop=loop, - 错误类型=type(e).__name__, - 错误信息=str(e), - ) - except Exception: - pass + tm_detected, tm_x = template_match_fallback( + analyser, pic_new, rx, ry, width, height, y_pianyi_val, loop, + ) + if tm_detected: + detected = True + detected_x = tm_x if detected and detected_x is not None: # 重置连续失败计数 diff --git a/douyin/detection/detection_pkg/template_match_helpers.py b/douyin/detection/detection_pkg/template_match_helpers.py new file mode 100644 index 0000000..0759f69 --- /dev/null +++ b/douyin/detection/detection_pkg/template_match_helpers.py @@ -0,0 +1,247 @@ +"""finder.py 的辅助函数:模板匹配兜底。 + +把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"逻辑(226 行) +抽出来,便于独立测试与维护。 +""" +from __future__ import annotations + +import os +import time +from typing import Any, Optional + + +def template_match_fallback( + analyser: Any, + pic_new: Any, # PIL.Image (RGBA) + rx: int, + ry: int, + width: int, + height: int, + y_pianyi_val: int, + loop: int, +) -> tuple[bool, Optional[int]]: + """像素检测未命中时使用 OpenCV 模板匹配作为兜底。 + + 返回 (detected, detected_x_in_1080_basis)。失败/异常返回 (False, None)。 + """ + try: + import cv2 + import numpy as np + + # 获取模板路径 + try: + from douyin.core import path_config + + template_path = path_config.get_assets_dir() + "/fudai.png" + except Exception: + base_dir = os.path.dirname(os.path.abspath(__file__)) + template_path = os.path.join(base_dir, "assets", "fudai.png") + + if not os.path.exists(template_path): + return False, None + + try: + template_threshold = float( + getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 + ) + except Exception: + template_threshold = 0.7 + + template = cv2.imread(template_path, cv2.IMREAD_COLOR) + if template is None: + return False, None + + pic_rgb = pic_new.convert("RGB") + screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) + + # 搜索区域:X=156-269(1080基准),Y=351-451(2400基准) + x1 = max(0, 156 * rx // 1080) + x2 = min(width, 269 * rx // 1080) + y_top = max(0, 351 * ry // 2400 + y_pianyi_val) + y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val) + + if not (x1 < x2 and y_top < y_bottom): + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-坐标无效", + loop=loop, + x1=x1, + x2=x2, + y_top=y_top, + y_bottom=y_bottom, + 截图尺寸=f"{width}x{height}", + 分辨率=f"{rx}x{ry}", + ) + except Exception: + pass + return False, None + + search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] + if search_roi.size <= 0: + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-搜索区域为空", + loop=loop, + 搜索区域=f"({x1},{y_top})-({x2},{y_bottom})", + 截图尺寸=f"{width}x{height}", + ) + except Exception: + pass + return False, None + + th, tw = template.shape[:2] + rh, rw = search_roi.shape[:2] + + # 保存搜索区域截图到 last_match.png(仅用于调试) + _save_last_match_debug(analyser, search_roi, loop, x1, x2, y_top, y_bottom, rw, rh) + + # 如果模板太大,缩小模板 + if th > rh or tw > rw: + scale = min(rh / max(th, 1), rw / max(tw, 1)) + if scale > 0: + template = cv2.resize( + template, + (max(1, int(tw * scale)), max(1, int(th * scale))), + ) + th, tw = template.shape[:2] + + if not (th <= rh and tw <= rw): + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-尺寸不匹配", + loop=loop, + 模板尺寸=f"{tw}x{th}", + 搜索区域尺寸=f"{rw}x{rh}", + 条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})", + ) + except Exception: + pass + return False, None + + # 执行模板匹配 + res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) + + _save_template_match_attempt_log(analyser, search_roi) + + try: + analyser._log_kv( + "[找福袋图标] 模板匹配兜底", + loop=loop, + 匹配分数=round(max_val, 4), + 阈值=template_threshold, + 是否通过=bool(max_val >= template_threshold), + 搜索区域=f"({x1},{y_top})-({x2},{y_bottom})", + 搜索区域尺寸=f"{rw}x{rh}", + 模板尺寸=f"{tw}x{th}", + 截图尺寸=f"{width}x{height}", + 分辨率=f"{rx}x{ry}", + ) + except Exception: + pass + + if max_val < template_threshold: + return False, None + + _save_template_match_success(analyser, search_roi) + + # 命中:计算 1080 基准 x 坐标 + detected_x_in_roi = max_loc[0] + detected_x = int((x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)) + try: + analyser.last_find_fudai_time = time.time() + except Exception: + pass + return True, detected_x + except Exception as e: + try: + analyser._log_kv( + "[找福袋图标] 模板匹配异常", + loop=loop, + 错误类型=type(e).__name__, + 错误信息=str(e), + ) + except Exception: + pass + return False, None + + +def _save_last_match_debug( + analyser: Any, search_roi: Any, loop: int, x1: int, x2: int, + y_top: int, y_bottom: int, rw: int, rh: int, +) -> None: + try: + import cv2 + + base_dir = os.path.dirname(os.path.abspath(__file__)) + pic_base = os.path.join(base_dir, "pic") + match_dir = os.path.join(pic_base, "template_match") + os.makedirs(match_dir, exist_ok=True) + last_match_path = os.path.join(match_dir, "last_match.png") + save_success = cv2.imwrite(last_match_path, search_roi) + if save_success: + try: + analyser._log_kv( + "[找福袋图标] 已保存搜索区域截图", + loop=loop, + 文件路径=last_match_path, + 搜索区域尺寸=f"{rw}x{rh}", + 搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})", + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "[找福袋图标] 保存搜索区域截图失败", + loop=loop, + 文件路径=last_match_path, + ) + except Exception: + pass + except Exception as save_err: + try: + analyser._log_kv( + "[找福袋图标] 保存搜索区域截图异常", + loop=loop, + 错误类型=type(save_err).__name__, + 错误信息=str(save_err), + ) + except Exception: + pass + + +def _save_template_match_attempt_log(analyser: Any, search_roi: Any) -> None: + """保存"实时尝试"截图(双截图记录用)。""" + try: + import cv2 + from PIL import Image as PILImage + from douyin.handlers import douyin_screenshot_manager + + search_roi_pil = PILImage.fromarray( + cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB) + ) + douyin_screenshot_manager.save_latest_attempt( + search_roi_pil, + operation_type="template_match", + ) + except Exception: + pass + + +def _save_template_match_success(analyser: Any, search_roi: Any) -> None: + """命中时保存成功识别存档截图。""" + try: + import cv2 + from PIL import Image as PILImage + from douyin.handlers import douyin_screenshot_manager + + search_roi_pil = PILImage.fromarray( + cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB) + ) + douyin_screenshot_manager.save_last_success( + search_roi_pil, + operation_type="template_match", + ) + except Exception: + pass diff --git a/tests/test_template_match_helpers.py b/tests/test_template_match_helpers.py new file mode 100644 index 0000000..1742560 --- /dev/null +++ b/tests/test_template_match_helpers.py @@ -0,0 +1,139 @@ +"""单元测试:douyin/detection/detection_pkg/template_match_helpers.py + +只覆盖纯逻辑路径与异常吞噬: +- 模板文件不存在 → 返回 (False, None) +- OpenCV 导入失败 / 模板读取失败 → 异常吞噬 +- 命中/未命中分数对比 +""" +from __future__ import annotations + +import os +from unittest.mock import MagicMock, patch + +import pytest + +from douyin.detection.detection_pkg import template_match_helpers as h + + +def _make_analyser(): + a = MagicMock() + a._log_kv = MagicMock() + a.fudai_template_match_threshold = 0.7 + return a + + +def test_template_match_missing_template_file_returns_false(monkeypatch, tmp_path): + a = _make_analyser() + fake_assets = tmp_path / "no_assets" + monkeypatch.setattr( + "douyin.core.path_config.get_assets_dir", + lambda: str(fake_assets), + ) + pic = MagicMock() + detected, x = h.template_match_fallback( + a, pic, rx=1080, ry=2400, + width=1080, height=2400, y_pianyi_val=0, loop=0, + ) + assert detected is False + assert x is None + + +def test_template_match_outer_exception_swallowed(monkeypatch): + a = _make_analyser() + # 让 cv2 import 抛错触发外层 except + monkeypatch.setitem(__import__("sys").modules, "cv2", None) + pic = MagicMock() + detected, x = h.template_match_fallback( + a, pic, rx=1080, ry=2400, + width=1080, height=2400, y_pianyi_val=0, loop=0, + ) + # cv2=None 时 .imread 调用抛 AttributeError → 被吞噬 + assert detected is False + assert x is None + + +def test_template_match_threshold_attr_not_a_number(monkeypatch, tmp_path): + """threshold 异常时回退到 0.7""" + a = _make_analyser() + a.fudai_template_match_threshold = "not_a_number" + fake_assets = tmp_path / "assets" + fake_assets.mkdir() + (fake_assets / "fudai.png").write_bytes(b"not_a_real_png") + monkeypatch.setattr( + "douyin.core.path_config.get_assets_dir", + lambda: str(fake_assets), + ) + pic = MagicMock() + # cv2.imread 会返回 None(不是真 PNG),触发"模板读取失败"分支 + detected, x = h.template_match_fallback( + a, pic, rx=1080, ry=2400, + width=1080, height=2400, y_pianyi_val=0, loop=0, + ) + assert detected is False + + +def test_template_match_full_pipeline_no_match(tmp_path, monkeypatch): + """阈值设到 1.01(不可达)→ 必然不匹配,验证阈值分支。""" + cv2 = pytest.importorskip("cv2") + import numpy as np + from PIL import Image + + a = _make_analyser() + a.fudai_template_match_threshold = 1.01 # 不可达,必然不匹配 + + fake_assets = tmp_path / "assets" + fake_assets.mkdir() + np.random.seed(7) + template = np.random.randint(0, 255, (30, 30, 3), dtype=np.uint8) + cv2.imwrite(str(fake_assets / "fudai.png"), template) + monkeypatch.setattr( + "douyin.core.path_config.get_assets_dir", + lambda: str(fake_assets), + ) + + pic_arr = np.full((2400, 1080, 4), 255, dtype=np.uint8) + pic = Image.fromarray(pic_arr, mode="RGBA") + + detected, x = h.template_match_fallback( + a, pic, rx=1080, ry=2400, + width=1080, height=2400, y_pianyi_val=0, loop=0, + ) + assert detected is False + assert x is None + + +def test_template_match_full_pipeline_perfect_match(tmp_path, monkeypatch): + """构造一张包含模板的图像 → 模板匹配应命中""" + cv2 = pytest.importorskip("cv2") + import numpy as np + from PIL import Image + + a = _make_analyser() + + fake_assets = tmp_path / "assets" + fake_assets.mkdir() + # 创建一个 30x30 的明显图案作为模板 + np.random.seed(0) + template = np.random.randint(0, 255, (30, 30, 3), dtype=np.uint8) + cv2.imwrite(str(fake_assets / "fudai.png"), template) + monkeypatch.setattr( + "douyin.core.path_config.get_assets_dir", + lambda: str(fake_assets), + ) + + # 构造一张图:把模板嵌入到搜索区域内(X=156-269, Y=351-451) + pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8) + pic_arr[..., 3] = 255 # alpha + embed_y, embed_x = 380, 200 # 都在搜索区域内 + # cv2 imread 是 BGR,put 时转回 RGB;这里直接用 numpy 嵌入相同 BGR 数组 + pic_arr[embed_y:embed_y + 30, embed_x:embed_x + 30, :3] = template[..., ::-1] + pic = Image.fromarray(pic_arr, mode="RGBA") + + detected, x = h.template_match_fallback( + a, pic, rx=1080, ry=2400, + width=1080, height=2400, y_pianyi_val=0, loop=0, + ) + assert detected is True + # 检测到的 x 应当在嵌入位置附近(embed_x + tw//2 = 200 + 15 = 215,1080 基准下相同) + assert x is not None + assert abs(x - (embed_x + 15)) <= 5