refactor(finder): 抽 check_have_fudai_with_ready_screenshot 中"模板匹配兜底"块到 finder_template_match

将 226 行的"OpenCV 模板匹配兜底"独立块抽到独立模块。
当像素检测未命中时,调用 cv2.matchTemplate 在指定区域查找福袋图标。

helper 接受 (analyser, detected, detected_x, pic_new, width, height, rx, ry,
y_pianyi_val, loop) 参数,返回更新后的 (detected, detected_x)。

finder.py: 944 → 726 行 (-218)
新增 finder_template_match.py: 257 行

finder.py 跌破 800 行(1438 → 726,本会话累计削减 712 行 = -50%)

验证:
- pytest 1013 passed
- compile OK

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 13:17:18 +08:00
1 parent 0bd71a5e76
commit 411fd96804
2 files changed
+264 -225

No files matched your search

+7 -225
View File
@@ -581,232 +581,14 @@ def check_have_fudai_with_ready_screenshot(
pass
# 像素检测未命中时,使用模板匹配作为兜底
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
from douyin.detection.detection_pkg.finder_template_match import (
template_match_fallback,
)
detected, detected_x = template_match_fallback(
analyser, detected, detected_x, pic_new,
width, height, rx, ry, y_pianyi_val, loop,
)
if detected and detected_x is not None:
# 重置连续失败计数
consecutive_failures = 0
@@ -0,0 +1,257 @@
"""find_fudai 辅助:模板匹配兜底(OpenCV)
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
当像素检测未命中时,使用 cv2.matchTemplate 在指定区域查找福袋图标。
"""
from __future__ import annotations
import os
import time
from typing import Any, Tuple
def template_match_fallback(
analyser: Any,
detected: bool,
detected_x,
pic_new,
width: int,
height: int,
rx: int,
ry: int,
y_pianyi_val: int,
loop: int,
) -> Tuple[bool, Any]:
"""像素检测未命中时的 OpenCV 模板匹配兜底。
返回更新后的 (detected, detected_x)。
"""
# 像素检测未命中时,使用模板匹配作为兜底
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
return detected, detected_x