chore(finder): 删除 check_have_fudai_with_ready_screenshot 中 return False 之后的不可达死代码

第 938-1431 行(共 494 行)位于函数 return 语句之后,永远不会执行。
这是早期像素检测改用模板匹配后的遗留代码。函数末尾的模块级注释
"像素检测代码已删除,使用模板匹配替代" 已说明该段代码无用。

验证:
- AST 解析通过
- pytest 1013 passed
- 函数边界从 19-1431 缩到 19-936

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 07:54:25 +08:00
1 parent 66eb05e6b1
commit b9f0389e58
1 file changed
-494
-494
View File
@@ -935,500 +935,6 @@ def check_have_fudai_with_ready_screenshot(
pass
return False
try:
retry_delay_s = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3
)
except Exception:
retry_delay_s = 0.3
try:
max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 2.5) or 2.5)
except Exception:
max_wait_s = 2.5
if retry_delay_s < 0.15:
retry_delay_s = 0.15
if max_wait_s < 0:
max_wait_s = 0.0
try:
analyser._log_kv(
"[找福袋图标] 开始",
f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready},使用模板匹配",
)
except Exception:
pass
detected_any = False
detected_x = None
# 检查OpenCV是否可用
try:
import cv2
import numpy as np
except Exception:
try:
analyser._log_kv(
"[找福袋图标] 错误", "OpenCV/numpy不可用,无法使用模板匹配"
)
except Exception:
pass
return False
# 获取模板路径
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 not os.path.exists(template_path):
try:
analyser._log_kv("[找福袋图标] 错误", f"模板文件不存在: {template_path}")
except Exception:
pass
return False
# 获取匹配阈值
try:
template_threshold = float(
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
)
except Exception:
template_threshold = 0.7
# 完全基于时间限制,不使用次数限制
while (time.time() - func_start) < max_wait_s:
attempt_start = time.time()
attempt_count += 1
# Reuse external screenshot only on first attempt if provided
if not (screenshot_ready and attempt_count == 1):
try:
analyser._shot_and_diagnose(
"找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False
)
except Exception:
pass
try:
screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR)
if screenshot_img is None:
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR)
except Exception:
pass
if screenshot_img is None:
elapsed = time.time() - func_start
if elapsed < max_wait_s:
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
continue
except Exception:
elapsed = time.time() - func_start
if elapsed < max_wait_s:
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
continue
# Resolution ratios
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
# 定义搜索区域(仅在更小的范围内寻找福袋图标)
# X范围:157-269(1080基准) # 左上角 X 改为图片中的坐标 x=157(右下不变)
# Y范围:354-451(2400基准) # 左上角 Y 改为图片中的坐标 y=354(右下不变)
search_x1 = max(0, 157 * rx // 1080)
search_x2 = min(screenshot_img.shape[1], 269 * rx // 1080)
search_y1_base = 354 * ry // 2400 + y_pianyi_val
search_y2_base = 451 * ry // 2400 + y_pianyi_val
search_y1 = max(0, search_y1_base)
search_y2 = min(screenshot_img.shape[0], search_y2_base)
if search_x1 >= search_x2 or search_y1 >= search_y2:
elapsed = time.time() - func_start
if elapsed < max_wait_s:
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
continue
# 裁剪搜索区域
search_roi = screenshot_img[search_y1:search_y2, search_x1:search_x2]
# 读取模板
try:
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is None:
try:
analyser._log_kv(
"[找福袋图标] 错误", f"无法读取模板文件: {template_path}"
)
except Exception:
pass
elapsed = time.time() - func_start
if elapsed < max_wait_s:
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
continue
except Exception as e:
try:
analyser._log_kv("[找福袋图标] 错误", f"读取模板文件异常: {str(e)}")
except Exception:
pass
elapsed = time.time() - func_start
if elapsed < max_wait_s:
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
continue
# 检查模板和搜索区域尺寸
th, tw = template.shape[:2]
rh, rw = search_roi.shape[:2]
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]
# 执行模板匹配(使用彩色匹配)
try:
template_match_start = time.time()
# 详细日志:记录搜索区域和模板信息
try:
analyser._log_kv(
"[找福袋图标] 模板匹配开始",
f"搜索区域",
search_x1=search_x1,
search_x2=search_x2,
search_y1=search_y1,
search_y2=search_y2,
search_width=search_x2 - search_x1,
search_height=search_y2 - search_y1,
template_width=tw,
template_height=th,
template_path=template_path,
阈值=template_threshold,
匹配模式="彩色(BGR)",
)
except Exception:
pass
# 使用彩色匹配(BGR三通道)
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"
)
# 保存调试图像(匹配前)- 使用完整截图
screenshot_pil = PILImage.fromarray(
cv2.cvtColor(screenshot_img, cv2.COLOR_BGR2RGB)
)
debug_path = douyin_screenshot_manager.save_debug_image(
screenshot_pil,
operation_type="template_match",
picname="fudai_icon",
step="before_match",
coords=(search_x1, search_y1, search_x2, search_y2),
extra_info={
"template": (
os.path.basename(template_path) if template_path else ""
),
"template_size": f"{tw}x{th}",
"search_size": f"{search_x2-search_x1}x{search_y2-search_y1}",
"threshold": template_threshold,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"模板匹配前保存",
path=debug_path,
coords=f"({search_x1},{search_y1})-({search_x2},{search_y2})",
)
except Exception:
pass
except Exception:
pass
template_match_elapsed = (time.time() - template_match_start) * 1000
# 详细日志:记录匹配结果
try:
analyser._log_kv(
"[找福袋图标] 模板匹配结果",
f"匹配分数={round(max_val, 4)},阈值={template_threshold}",
耗时毫秒=round(template_match_elapsed, 2),
是否通过=bool(max_val >= template_threshold),
最小分数=round(_min_val, 4),
最佳位置=f"({max_loc[0]}, {max_loc[1]})",
)
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"
)
# 保存带匹配结果的调试图像(带匹配框)- 使用完整截图
screenshot_pil = PILImage.fromarray(
cv2.cvtColor(screenshot_img, cv2.COLOR_BGR2RGB)
)
# 计算匹配位置在完整截图中的坐标
match_x_in_roi = max_loc[0]
match_y_in_roi = max_loc[1]
match_x1 = search_x1 + match_x_in_roi
match_y1 = search_y1 + match_y_in_roi
match_x2 = search_x1 + match_x_in_roi + tw
match_y2 = search_y1 + match_y_in_roi + th
match_coords = (match_x1, match_y1, match_x2, match_y2)
debug_path = douyin_screenshot_manager.save_debug_image(
screenshot_pil,
operation_type="template_match",
picname="fudai_icon",
step="matched",
coords=(
search_x1,
search_y1,
search_x2,
search_y2,
), # 搜索区域坐标
extra_info={
"match_score": round(max_val, 4),
"match_location": f"({max_loc[0]},{max_loc[1]})",
"match_coords": match_coords, # 匹配位置坐标
"template_size": f"{tw}x{th}",
"threshold": template_threshold,
"passed": True,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"模板匹配成功保存",
path=debug_path,
score=round(max_val, 4),
location=f"({max_loc[0]},{max_loc[1]})",
)
except Exception:
pass
except Exception:
pass
# 计算检测到的X坐标(1080基准)
detected_x_in_roi = max_loc[0]
detected_x = int(
(search_x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)
)
detected_y_in_roi = max_loc[1]
detected_y = int(
(search_y1 + detected_y_in_roi + th // 2) * 2400.0 / max(1, ry)
)
detected_any = True
# 保存匹配位置的图片
try:
# 计算匹配区域在原图中的坐标(扩大一些范围以便查看上下文)
margin = 20 # 扩大20像素的边距
match_x1 = max(0, search_x1 + detected_x_in_roi - margin)
match_y1 = max(0, search_y1 + detected_y_in_roi - margin)
match_x2 = min(
screenshot_img.shape[1],
search_x1 + detected_x_in_roi + tw + margin,
)
match_y2 = min(
screenshot_img.shape[0],
search_y1 + detected_y_in_roi + th + margin,
)
# 裁剪匹配区域
match_roi = screenshot_img[match_y1:match_y2, match_x1:match_x2]
# 保存到 pic/template_match/ 目录
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)
# 文件名包含时间戳和匹配分数
timestamp = int(time.time() * 1000)
score_str = f"{max_val:.4f}".replace(".", "_")
match_filename = f"fudai_match_{timestamp}_score_{score_str}.png"
match_path = os.path.join(match_dir, match_filename)
# 检查裁剪区域是否有效
if match_roi.size == 0:
analyser._log_kv(
"[找福袋图标] 警告",
"匹配区域裁剪后为空,跳过保存",
区域坐标=f"({match_x1}, {match_y1}) - ({match_x2}, {match_y2})",
)
else:
# 保存图片
save_success = cv2.imwrite(match_path, match_roi)
# 验证文件是否真的保存成功
file_exists = os.path.exists(match_path)
file_size = os.path.getsize(match_path) if file_exists else 0
analyser._log_kv(
"[找福袋图标] 已保存匹配位置图片",
f"路径: {match_path}",
匹配区域=f"({match_x1}, {match_y1}) - ({match_x2}, {match_y2})",
区域大小=f"{match_x2 - match_x1}x{match_y2 - match_y1}",
ROI尺寸=f"{match_roi.shape[1]}x{match_roi.shape[0]}",
cv2保存返回值=save_success,
文件存在=file_exists,
文件大小字节=file_size,
)
if not file_exists or file_size == 0:
analyser._log_kv(
"[找福袋图标] 警告",
"保存的图片文件不存在或大小为0",
路径=match_path,
)
else:
# 保存成功,输出绝对路径方便查看
abs_path = os.path.abspath(match_path)
analyser._log_kv(
"[找福袋图标] 图片保存成功",
f"绝对路径: {abs_path}",
)
except Exception as e:
try:
analyser._log_kv(
"[找福袋图标] 保存匹配位置图片失败",
f"异常: {str(e)}",
)
except Exception:
pass
try:
analyser.last_find_fudai_time = time.time()
analyser._log_kv(
"[找福袋图标] 模板匹配命中",
f"检测到福袋图标",
x=detected_x,
y=detected_y,
匹配分数=round(max_val, 4),
x_in_roi=detected_x_in_roi,
y_in_roi=detected_y_in_roi,
模板中心偏移=f"({tw//2}, {th//2})",
实际屏幕坐标=f"({detected_x}, {detected_y})",
)
except Exception:
pass
break
else:
# 未命中时也记录日志
try:
analyser._log_kv(
"[找福袋图标] 模板匹配未命中",
f"匹配分数={round(max_val, 4)} < 阈值={template_threshold}",
差值=round(template_threshold - max_val, 4),
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv(
"[找福袋图标] 模板匹配异常",
f"异常: {str(e)}",
异常类型=type(e).__name__,
)
except Exception:
pass
# 检查是否还有剩余时间
elapsed = time.time() - func_start
if elapsed < max_wait_s:
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
try:
total_elapsed = time.time() - func_start
analyser._log_kv(
"[找福袋图标] 结束",
"检测完成",
detected=bool(detected_any and detected_x is not None),
elapsed_ms=int(total_elapsed * 1000),
)
except Exception:
pass
# 与原始 fudai.py 的 check_have_fudai 行为保持一致:
# 返回福袋图标的 x 坐标(1080 基准坐标),未找到返回 False。
return int(detected_x) if detected_x is not None else False
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========