FudaiDetector.detect_by_template 拆出(957→655,瘦身 302 行)

把 douyin/fudai/douyin_fudai_finder_pkg/detector.py 的 FudaiDetector.detect_by_template
(306 行 / 4 个 self.X)搬到独立子模块 detect_by_template.py(321 行)。

策略:
- self.analyser → analyser(参数)
- self.rx → rx(参数)
- 类方法保留为 1 行 forwarding:
    def detect_by_template(self, pic, region):
        return _impl(self.analyser, self.rx, pic, region)
- detector.py 内顶部 import detect_by_template 模块的实现

回归:
- 2 个文件 compileall 通过
- pytest 355 passed / 1 skipped
- FudaiFinder() 实例化正常,FudaiDetector.detect_by_template 类方法仍可访问
- module-level detect_by_template 可独立调用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-21 20:31:27 +08:00
1 parent 57d99f3459
commit 2d928c3856
2 files changed
+324 -305

No files matched your search

@@ -0,0 +1,321 @@
"""douyin_fudai_finder_pkg.detect_by_template - 模板匹配检测福袋图标。
从 FudaiDetector 类拆出,纯函数形式接受 (analyser, rx, pic, region)。
类内保留 1 行 forwarding 调用本函数。
"""
from __future__ import annotations
# pylint: disable=E1101
import time
from typing import Any, Dict, Optional
from PIL import Image
def detect_by_template(analyser, rx: int, pic: Image.Image, region: Dict) -> Optional[int]:
"""使用模板匹配在指定区域查找福袋图标(优化版:多方法+预处理)
参数:
pic: PIL Image对象
region: 搜索区域配置
返回:
检测到的X坐标(1080基准),未找到返回None
"""
# pyright: ignore[reportUnknownMemberType, reportAttributeAccessIssue]
start_time = time.time()
try:
import cv2 # type: ignore[import-untyped]
import numpy as np
except ImportError:
return None
# 获取模板路径
try:
# 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 not os.path.exists(template_path):
return None
# 获取匹配阈值
try:
threshold = float(
getattr(analyser, "fudai_template_match_threshold", 0.6) or 0.6
)
except Exception:
threshold = 0.6 # 降低默认阈值,因为添加了多种匹配方法
# 读取模板(彩色和灰度)
template_color = cv2.imread(template_path, cv2.IMREAD_COLOR) # type: ignore[attr-defined, misc]
template_gray = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) # type: ignore[attr-defined, misc]
if template_color is None or template_gray is None:
return None
width, height = pic.size
pic_rgb = pic.convert("RGB")
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) # type: ignore[attr-defined, misc]
# 提取搜索区域(扩大Y范围用于模板匹配,提高成功率)
if "y_top" in region:
# 中间区域(矩形)
x1 = max(0, min(region.get("x1", 0), width))
x2 = max(0, min(region.get("x2", width), width))
y_top = max(0, min(region.get("y_top", 0), height))
y_bottom = max(0, min(region.get("y_bottom", height), height))
else:
# 水平带区域:扩大Y范围用于模板匹配(从7像素扩大到30像素)
x1 = max(0, min(region.get("x1", 0), width))
x2 = max(0, min(region.get("x2", width), width))
scan_y = region.get("y", 0)
y_range = region.get("y_range", 7)
# 模板匹配需要更大的Y范围
template_match_y_range = max(30, y_range * 4) # 至少30像素
y_top = max(0, scan_y - template_match_y_range // 2)
y_bottom = min(height, scan_y + template_match_y_range // 2 + 1)
if x1 >= x2 or y_top >= y_bottom:
return None
search_roi_bgr = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
if search_roi_bgr.size == 0:
return None
# 转换为灰度图(用于灰度匹配)
search_roi_gray = cv2.cvtColor(search_roi_bgr, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined, misc]
# 图像预处理:增强对比度和去噪
try:
# 直方图均衡化(增强对比度)
search_roi_gray_enhanced = cv2.equalizeHist(search_roi_gray) # type: ignore[attr-defined, misc]
template_gray_enhanced = cv2.equalizeHist(template_gray) # type: ignore[attr-defined, misc]
except Exception:
search_roi_gray_enhanced = search_roi_gray
template_gray_enhanced = template_gray
th, tw = template_color.shape[:2]
rh, rw = search_roi_bgr.shape[:2]
# 多尺度+多方法模板匹配
best_score = -1.0
best_x = None
best_scale = 1.0
best_method = ""
# 缩放比例范围:0.7 到 1.3(扩大范围)
scales = [1.0, 0.9, 1.1, 0.8, 1.2, 0.7, 1.3]
# 多种匹配方法(按优先级排序)
match_methods = [
(cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关系数(最常用)
(cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关匹配
(cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化平方差(值越小越好)
]
for scale in scales:
scaled_tw = max(1, int(tw * scale))
scaled_th = max(1, int(th * scale))
# 如果缩放后的模板太大,跳过
if scaled_th > rh or scaled_tw > rw:
continue
# 缩放模板(彩色和灰度)
scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
scaled_template_gray_enhanced = cv2.resize(template_gray_enhanced, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
# 尝试多种匹配方法
for method, method_name in match_methods:
try:
# 方法1:彩色匹配
res_color = cv2.matchTemplate( # type: ignore[attr-defined, misc]
search_roi_bgr, scaled_template_color, method
)
if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc]
score = 1.0 - max_val # SQDIFF值越小越好,转换为越大越好
else:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc]
score = max_val
if score > best_score:
best_score = score
best_x = max_loc[0]
best_scale = scale
best_method = f"{method_name}_color"
# 方法2:灰度匹配(更稳定,不受光照影响)
res_gray = cv2.matchTemplate( # type: ignore[attr-defined, misc]
search_roi_gray, scaled_template_gray, method
)
if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc]
score = 1.0 - max_val
else:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc]
score = max_val
if score > best_score:
best_score = score
best_x = max_loc[0]
best_scale = scale
best_method = f"{method_name}_gray"
# 方法3:增强对比度后的灰度匹配
res_gray_enhanced = cv2.matchTemplate( # type: ignore[attr-defined, misc]
search_roi_gray_enhanced, scaled_template_gray_enhanced, method
)
if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc]
res_gray_enhanced
)
score = 1.0 - max_val
else:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc]
res_gray_enhanced
)
score = max_val
if score > best_score:
best_score = score
best_x = max_loc[0]
best_scale = scale
best_method = f"{method_name}_gray_enhanced"
except Exception:
continue
# 如果所有方法都失败,回退到单尺度单方法匹配
if best_score < 0:
# 如果模板太大,缩小模板
if th > rh or tw > rw:
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale > 0:
template_color = cv2.resize( # type: ignore[attr-defined, misc]
template_color,
(max(1, int(tw * scale)), max(1, int(th * scale))),
)
template_gray = cv2.resize( # type: ignore[attr-defined, misc]
template_gray,
(max(1, int(tw * scale)), max(1, int(th * scale))),
)
th, tw = template_color.shape[:2]
if th <= rh and tw <= rw:
try:
res = cv2.matchTemplate( # type: ignore[attr-defined, misc]
search_roi_bgr, template_color, cv2.TM_CCOEFF_NORMED
)
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined, misc]
best_score = max_val
best_x = max_loc[0]
best_scale = 1.0
best_method = "CCOEFF_NORMED_color_fallback"
except Exception:
best_score = -1.0
best_x = None
best_scale = 1.0
best_method = ""
else:
best_score = -1.0
best_x = None
best_scale = 1.0
best_method = ""
max_val = best_score
max_loc = (best_x, 0) if best_x is not None else (0, 0)
elapsed = (time.time() - start_time) * 1000
try:
analyser._log_kv(
"[福袋查找] 模板匹配",
f"{region['name']}",
elapsed_ms=round(elapsed, 2),
score=round(max_val, 4),
threshold=threshold,
passed=bool(max_val >= threshold),
best_scale=round(best_scale, 2) if best_score >= 0 else None,
best_method=best_method if best_method else None,
)
except Exception:
pass
# 保存模板匹配的调试图像(无论成功与否)- 使用完整截图
try:
from douyin.handlers import douyin_screenshot_manager
# Image 已在文件顶部导入
# 使用完整截图而不是搜索区域ROI
pic_rgb = pic.convert("RGB")
# 计算匹配位置在完整截图中的坐标(如果匹配成功)
match_coords = None
if max_val >= threshold and best_x is not None:
try:
best_tw = int(tw * best_scale) if best_score >= 0 else tw
best_th = int(th * best_scale) if best_score >= 0 else th
# 匹配位置在ROI内的坐标
match_x1_in_roi = best_x
match_y1_in_roi = 0
match_x2_in_roi = best_x + best_tw
match_y2_in_roi = best_th
# 转换为完整截图坐标
match_x1 = x1 + match_x1_in_roi
match_y1 = y_top + match_y1_in_roi
match_x2 = x1 + match_x2_in_roi
match_y2 = y_top + match_y2_in_roi
match_coords = (match_x1, match_y1, match_x2, match_y2)
except Exception:
pass
# 使用搜索区域坐标作为主要标注,匹配位置作为额外信息
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="template_match",
picname="fudai_icon",
step="matched" if max_val >= threshold else "failed",
coords=(x1, y_top, x2, y_bottom), # 搜索区域坐标
extra_info={
"region": region.get("name", "unknown"),
"score": round(max_val, 4),
"threshold": threshold,
"passed": bool(max_val >= threshold),
"best_scale": round(best_scale, 2) if best_score >= 0 else None,
"template_size": f"{tw}x{th}",
"search_size": f"{rw}x{rh}",
"match_coords": match_coords, # 匹配位置坐标(如果匹配成功)
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
f"模板匹配{'成功' if max_val >= threshold else '失败'}",
path=debug_path,
region=region.get("name", "unknown"),
score=round(max_val, 4),
threshold=threshold,
)
except Exception:
pass
except Exception:
pass
if max_val >= threshold:
detected_x_in_roi = max_loc[0]
# 使用最佳匹配时的模板宽度计算中心点
best_tw = int(tw * best_scale) if best_score >= 0 else tw
detected_x = int(
(x1 + detected_x_in_roi + best_tw // 2) * 1080.0 / max(1, rx)
)
return detected_x
return None
@@ -13,6 +13,8 @@ from typing import Any, Dict, Optional, Tuple
from PIL import Image
from .detect_by_template import detect_by_template as _impl_detect_by_template
from douyin.core import path_config
# OCR 预处理接口
@@ -458,311 +460,7 @@ class FudaiDetector:
return None
def detect_by_template(self, pic: Image.Image, region: Dict) -> Optional[int]:
"""使用模板匹配在指定区域查找福袋图标(优化版:多方法+预处理)
参数:
pic: PIL Image对象
region: 搜索区域配置
返回:
检测到的X坐标(1080基准),未找到返回None
"""
# pyright: ignore[reportUnknownMemberType, reportAttributeAccessIssue]
start_time = time.time()
try:
import cv2 # type: ignore[import-untyped]
import numpy as np
except ImportError:
return None
# 获取模板路径
try:
# 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 not os.path.exists(template_path):
return None
# 获取匹配阈值
try:
threshold = float(
getattr(self.analyser, "fudai_template_match_threshold", 0.6) or 0.6
)
except Exception:
threshold = 0.6 # 降低默认阈值,因为添加了多种匹配方法
# 读取模板(彩色和灰度)
template_color = cv2.imread(template_path, cv2.IMREAD_COLOR) # type: ignore[attr-defined, misc]
template_gray = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) # type: ignore[attr-defined, misc]
if template_color is None or template_gray is None:
return None
width, height = pic.size
pic_rgb = pic.convert("RGB")
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) # type: ignore[attr-defined, misc]
# 提取搜索区域(扩大Y范围用于模板匹配,提高成功率)
if "y_top" in region:
# 中间区域(矩形)
x1 = max(0, min(region.get("x1", 0), width))
x2 = max(0, min(region.get("x2", width), width))
y_top = max(0, min(region.get("y_top", 0), height))
y_bottom = max(0, min(region.get("y_bottom", height), height))
else:
# 水平带区域:扩大Y范围用于模板匹配(从7像素扩大到30像素)
x1 = max(0, min(region.get("x1", 0), width))
x2 = max(0, min(region.get("x2", width), width))
scan_y = region.get("y", 0)
y_range = region.get("y_range", 7)
# 模板匹配需要更大的Y范围
template_match_y_range = max(30, y_range * 4) # 至少30像素
y_top = max(0, scan_y - template_match_y_range // 2)
y_bottom = min(height, scan_y + template_match_y_range // 2 + 1)
if x1 >= x2 or y_top >= y_bottom:
return None
search_roi_bgr = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
if search_roi_bgr.size == 0:
return None
# 转换为灰度图(用于灰度匹配)
search_roi_gray = cv2.cvtColor(search_roi_bgr, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined, misc]
# 图像预处理:增强对比度和去噪
try:
# 直方图均衡化(增强对比度)
search_roi_gray_enhanced = cv2.equalizeHist(search_roi_gray) # type: ignore[attr-defined, misc]
template_gray_enhanced = cv2.equalizeHist(template_gray) # type: ignore[attr-defined, misc]
except Exception:
search_roi_gray_enhanced = search_roi_gray
template_gray_enhanced = template_gray
th, tw = template_color.shape[:2]
rh, rw = search_roi_bgr.shape[:2]
# 多尺度+多方法模板匹配
best_score = -1.0
best_x = None
best_scale = 1.0
best_method = ""
# 缩放比例范围:0.7 到 1.3(扩大范围)
scales = [1.0, 0.9, 1.1, 0.8, 1.2, 0.7, 1.3]
# 多种匹配方法(按优先级排序)
match_methods = [
(cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关系数(最常用)
(cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关匹配
(cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化平方差(值越小越好)
]
for scale in scales:
scaled_tw = max(1, int(tw * scale))
scaled_th = max(1, int(th * scale))
# 如果缩放后的模板太大,跳过
if scaled_th > rh or scaled_tw > rw:
continue
# 缩放模板(彩色和灰度)
scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
scaled_template_gray_enhanced = cv2.resize(template_gray_enhanced, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
# 尝试多种匹配方法
for method, method_name in match_methods:
try:
# 方法1:彩色匹配
res_color = cv2.matchTemplate( # type: ignore[attr-defined, misc]
search_roi_bgr, scaled_template_color, method
)
if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc]
score = 1.0 - max_val # SQDIFF值越小越好,转换为越大越好
else:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc]
score = max_val
if score > best_score:
best_score = score
best_x = max_loc[0]
best_scale = scale
best_method = f"{method_name}_color"
# 方法2:灰度匹配(更稳定,不受光照影响)
res_gray = cv2.matchTemplate( # type: ignore[attr-defined, misc]
search_roi_gray, scaled_template_gray, method
)
if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc]
score = 1.0 - max_val
else:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc]
score = max_val
if score > best_score:
best_score = score
best_x = max_loc[0]
best_scale = scale
best_method = f"{method_name}_gray"
# 方法3:增强对比度后的灰度匹配
res_gray_enhanced = cv2.matchTemplate( # type: ignore[attr-defined, misc]
search_roi_gray_enhanced, scaled_template_gray_enhanced, method
)
if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc]
res_gray_enhanced
)
score = 1.0 - max_val
else:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc]
res_gray_enhanced
)
score = max_val
if score > best_score:
best_score = score
best_x = max_loc[0]
best_scale = scale
best_method = f"{method_name}_gray_enhanced"
except Exception:
continue
# 如果所有方法都失败,回退到单尺度单方法匹配
if best_score < 0:
# 如果模板太大,缩小模板
if th > rh or tw > rw:
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale > 0:
template_color = cv2.resize( # type: ignore[attr-defined, misc]
template_color,
(max(1, int(tw * scale)), max(1, int(th * scale))),
)
template_gray = cv2.resize( # type: ignore[attr-defined, misc]
template_gray,
(max(1, int(tw * scale)), max(1, int(th * scale))),
)
th, tw = template_color.shape[:2]
if th <= rh and tw <= rw:
try:
res = cv2.matchTemplate( # type: ignore[attr-defined, misc]
search_roi_bgr, template_color, cv2.TM_CCOEFF_NORMED
)
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined, misc]
best_score = max_val
best_x = max_loc[0]
best_scale = 1.0
best_method = "CCOEFF_NORMED_color_fallback"
except Exception:
best_score = -1.0
best_x = None
best_scale = 1.0
best_method = ""
else:
best_score = -1.0
best_x = None
best_scale = 1.0
best_method = ""
max_val = best_score
max_loc = (best_x, 0) if best_x is not None else (0, 0)
elapsed = (time.time() - start_time) * 1000
try:
self.analyser._log_kv(
"[福袋查找] 模板匹配",
f"{region['name']}",
elapsed_ms=round(elapsed, 2),
score=round(max_val, 4),
threshold=threshold,
passed=bool(max_val >= threshold),
best_scale=round(best_scale, 2) if best_score >= 0 else None,
best_method=best_method if best_method else None,
)
except Exception:
pass
# 保存模板匹配的调试图像(无论成功与否)- 使用完整截图
try:
from douyin.handlers import douyin_screenshot_manager
# Image 已在文件顶部导入
# 使用完整截图而不是搜索区域ROI
pic_rgb = pic.convert("RGB")
# 计算匹配位置在完整截图中的坐标(如果匹配成功)
match_coords = None
if max_val >= threshold and best_x is not None:
try:
best_tw = int(tw * best_scale) if best_score >= 0 else tw
best_th = int(th * best_scale) if best_score >= 0 else th
# 匹配位置在ROI内的坐标
match_x1_in_roi = best_x
match_y1_in_roi = 0
match_x2_in_roi = best_x + best_tw
match_y2_in_roi = best_th
# 转换为完整截图坐标
match_x1 = x1 + match_x1_in_roi
match_y1 = y_top + match_y1_in_roi
match_x2 = x1 + match_x2_in_roi
match_y2 = y_top + match_y2_in_roi
match_coords = (match_x1, match_y1, match_x2, match_y2)
except Exception:
pass
# 使用搜索区域坐标作为主要标注,匹配位置作为额外信息
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="template_match",
picname="fudai_icon",
step="matched" if max_val >= threshold else "failed",
coords=(x1, y_top, x2, y_bottom), # 搜索区域坐标
extra_info={
"region": region.get("name", "unknown"),
"score": round(max_val, 4),
"threshold": threshold,
"passed": bool(max_val >= threshold),
"best_scale": round(best_scale, 2) if best_score >= 0 else None,
"template_size": f"{tw}x{th}",
"search_size": f"{rw}x{rh}",
"match_coords": match_coords, # 匹配位置坐标(如果匹配成功)
},
)
if debug_path:
try:
self.analyser._log_kv(
"[调试图像]",
f"模板匹配{'成功' if max_val >= threshold else '失败'}",
path=debug_path,
region=region.get("name", "unknown"),
score=round(max_val, 4),
threshold=threshold,
)
except Exception:
pass
except Exception:
pass
if max_val >= threshold:
detected_x_in_roi = max_loc[0]
# 使用最佳匹配时的模板宽度计算中心点
best_tw = int(tw * best_scale) if best_score >= 0 else tw
detected_x = int(
(x1 + detected_x_in_roi + best_tw // 2) * 1080.0 / max(1, self.rx)
)
return detected_x
return None
return _impl_detect_by_template(self.analyser, self.rx, pic, region)
def detect(self, pic: Image.Image) -> Tuple[Optional[int], str]:
"""检测福袋图标位置(按优先级搜索,像素检测后需模板匹配确认)