Files
douyi_guaji_main/douyin/detection/detection_pkg/template_match_helpers.py
T
CodexandClaude Opus 4.7 a391c21f47 refactor(detection): 拆出 finder.py 模板匹配兜底(936→719,-217 行)
把 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) <noreply@anthropic.com>
2026-05-22 04:55:08 +08:00

248 lines
8.0 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.
"""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