把 finder.py 中两个像素扫描兜底块抽到 template_match_helpers: - numpy_pixel_scan:numpy 加速水平带扫描(126 行) - per_pixel_scan_fallback:numpy 失败时的逐像素扫描(166 行) - _is_target_pixel / _scan_one_row / _save_per_pixel_success:辅助函数 新增 10 个单元测试覆盖:无匹配 / 命中 / 无效 ROI / last_fudai_x 复用 / 异常吞噬 / 目标颜色范围判定。1320 → 1330 用例全过。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
548 lines
17 KiB
Python
548 lines
17 KiB
Python
"""finder.py 的辅助函数:模板匹配兜底。
|
||
|
||
把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"逻辑(226 行)
|
||
抽出来,便于独立测试与维护。
|
||
|
||
同时包含 numpy 加速像素扫描 + 逐像素扫描兜底的辅助函数。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import time
|
||
from typing import Any, Optional
|
||
|
||
|
||
def numpy_pixel_scan(
|
||
analyser: Any,
|
||
pic_new: Any, # PIL.Image (RGBA)
|
||
rx: int,
|
||
ry: int,
|
||
width: int,
|
||
height: int,
|
||
y_pianyi_val: int,
|
||
optimal_x_scaled: int,
|
||
) -> tuple[bool, Optional[int]]:
|
||
"""先尝试 numpy 加速扫描水平带(性能优化:批量处理)。
|
||
|
||
返回 (detected, detected_x_in_1080_basis)。失败/异常返回 (False, None)。
|
||
"""
|
||
try:
|
||
import numpy as _np
|
||
|
||
y0 = 354 * ry // 2400 + y_pianyi_val
|
||
x1 = max(0, 157 * rx // 1080)
|
||
x2 = min(width, 410 * rx // 1080)
|
||
y_top = max(0, y0 - 3)
|
||
y_bottom = min(height, y0 + 4)
|
||
|
||
if not (x1 < x2 and y_top < y_bottom):
|
||
return False, None
|
||
|
||
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
|
||
|
||
try:
|
||
from douyin.handlers import douyin_screenshot_manager
|
||
|
||
douyin_screenshot_manager.save_latest_attempt(
|
||
roi, operation_type="pixel_detect"
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
arr = _np.array(roi)
|
||
if arr.size == 0:
|
||
return False, None
|
||
|
||
r = arr[:, :, 0]
|
||
g = arr[:, :, 1]
|
||
b = arr[:, :, 2]
|
||
mask_center = (
|
||
(r >= 190) & (r <= 206)
|
||
& (g >= 173) & (g <= 196)
|
||
& (b >= 234) & (b <= 250)
|
||
)
|
||
cols = _np.sum(mask_center, axis=0)
|
||
valid_cols = cols >= 2
|
||
if not valid_cols.any():
|
||
return False, None
|
||
|
||
roi_width = x2 - x1
|
||
optimal_col = max(0, min(optimal_x_scaled - x1, roi_width - 1))
|
||
|
||
# 从最优位置开始,向左右两侧交替搜索
|
||
found_col = None
|
||
search_range = max(optimal_col, roi_width - optimal_col)
|
||
|
||
if valid_cols[optimal_col]:
|
||
found_col = optimal_col
|
||
else:
|
||
for offset in range(1, search_range + 1):
|
||
right_col = optimal_col + offset
|
||
if right_col < roi_width and valid_cols[right_col]:
|
||
found_col = right_col
|
||
break
|
||
left_col = optimal_col - offset
|
||
if left_col >= 0 and valid_cols[left_col]:
|
||
found_col = left_col
|
||
break
|
||
|
||
if found_col is None:
|
||
found_col = int(_np.argmax(valid_cols))
|
||
|
||
col_idx = found_col
|
||
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
|
||
|
||
try:
|
||
analyser.last_fudai_x = detected_x
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
from douyin.handlers import douyin_screenshot_manager
|
||
|
||
douyin_screenshot_manager.save_last_success(
|
||
roi, operation_type="pixel_detect"
|
||
)
|
||
pic_rgb_full = pic_new.convert("RGB")
|
||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||
pic_rgb_full,
|
||
operation_type="pixel_detect",
|
||
picname="fudai_icon",
|
||
step="detected",
|
||
coords=(x1, y_top, x2, y_bottom),
|
||
extra_info={
|
||
"detected_x": detected_x,
|
||
"detected_x_scaled": x1 + col_idx,
|
||
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
|
||
"resolution": f"{rx}x{ry}",
|
||
"result": "success",
|
||
},
|
||
)
|
||
if debug_path:
|
||
try:
|
||
analyser._log_kv(
|
||
"[调试图像]",
|
||
"福袋图标检测成功保存完整截图",
|
||
path=debug_path,
|
||
detected_x=detected_x,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
analyser.last_find_fudai_time = time.time()
|
||
except Exception:
|
||
pass
|
||
|
||
return True, detected_x
|
||
except (ImportError, ValueError, IndexError, AttributeError):
|
||
return False, None
|
||
|
||
|
||
def _is_target_pixel(px: Any) -> bool:
|
||
"""检查像素是否在目标颜色范围内。"""
|
||
if not (isinstance(px, tuple) and len(px) >= 3):
|
||
return False
|
||
return (
|
||
190 <= px[0] <= 206
|
||
and 173 <= px[1] <= 196
|
||
and 234 <= px[2] <= 250
|
||
)
|
||
|
||
|
||
def per_pixel_scan_fallback(
|
||
analyser: Any,
|
||
pic_new: Any,
|
||
rx: int,
|
||
ry: int,
|
||
y_pianyi_val: int,
|
||
) -> tuple[bool, Optional[int]]:
|
||
"""numpy 不可用或未命中时的逐像素扫描兜底。"""
|
||
try:
|
||
pix = pic_new.load()
|
||
pic_width, pic_height = pic_new.size
|
||
|
||
scan_x_start = 41 * rx // 1080
|
||
scan_x_end = min(410 * rx // 1080, pic_width)
|
||
scan_y = 403 * ry // 2400 + y_pianyi_val
|
||
|
||
try:
|
||
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
|
||
if (
|
||
last_fudai_x > 0
|
||
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
|
||
):
|
||
optimal_x_scaled = last_fudai_x * rx // 1080
|
||
else:
|
||
optimal_x_scaled = 169 * rx // 1080
|
||
except Exception:
|
||
optimal_x_scaled = 169 * rx // 1080
|
||
|
||
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
|
||
|
||
if not (0 <= scan_y < pic_height):
|
||
return False, None
|
||
|
||
for offset_y in [0, -1, 1, -2, 2]:
|
||
check_y = scan_y + offset_y
|
||
if not (0 <= check_y < pic_height):
|
||
continue
|
||
|
||
found_x = _scan_one_row(
|
||
pix, check_y, scan_x_start, scan_x_end, optimal_x_scaled
|
||
)
|
||
|
||
if found_x is not None:
|
||
detected_x = int(found_x * 1080.0 / max(1, rx))
|
||
try:
|
||
analyser.last_fudai_x = detected_x
|
||
except Exception:
|
||
pass
|
||
|
||
_save_per_pixel_success(
|
||
analyser, pic_new, scan_x_start, scan_y, scan_x_end,
|
||
pic_height, detected_x, found_x, rx, ry,
|
||
)
|
||
|
||
try:
|
||
analyser.last_find_fudai_time = time.time()
|
||
except Exception:
|
||
pass
|
||
return True, detected_x
|
||
return False, None
|
||
except Exception:
|
||
return False, None
|
||
|
||
|
||
def _scan_one_row(
|
||
pix: Any,
|
||
check_y: int,
|
||
scan_x_start: int,
|
||
scan_x_end: int,
|
||
optimal_x_scaled: int,
|
||
) -> Optional[int]:
|
||
"""在单行扫描目标像素:先查最优位置,然后左右交替,最后从左到右兜底。"""
|
||
# 先检查最优位置
|
||
try:
|
||
if _is_target_pixel(pix[optimal_x_scaled, check_y]):
|
||
return optimal_x_scaled
|
||
except (IndexError, TypeError):
|
||
pass
|
||
|
||
# 向左右两侧交替搜索
|
||
search_range = max(
|
||
optimal_x_scaled - scan_x_start,
|
||
scan_x_end - optimal_x_scaled,
|
||
)
|
||
for offset in range(1, search_range + 1):
|
||
right_x = optimal_x_scaled + offset
|
||
if right_x < scan_x_end:
|
||
try:
|
||
if _is_target_pixel(pix[right_x, check_y]):
|
||
return right_x
|
||
except (IndexError, TypeError):
|
||
pass
|
||
left_x = optimal_x_scaled - offset
|
||
if left_x >= scan_x_start:
|
||
try:
|
||
if _is_target_pixel(pix[left_x, check_y]):
|
||
return left_x
|
||
except (IndexError, TypeError):
|
||
pass
|
||
|
||
# 兜底:从左到右
|
||
for x_scaled in range(scan_x_start, scan_x_end):
|
||
try:
|
||
if _is_target_pixel(pix[x_scaled, check_y]):
|
||
return x_scaled
|
||
except (IndexError, TypeError):
|
||
continue
|
||
|
||
return None
|
||
|
||
|
||
def _save_per_pixel_success(
|
||
analyser: Any, pic_new: Any, scan_x_start: int, scan_y: int,
|
||
scan_x_end: int, pic_height: int, detected_x: int, found_x: int,
|
||
rx: int, ry: int,
|
||
) -> None:
|
||
try:
|
||
from douyin.handlers import douyin_screenshot_manager
|
||
|
||
detect_roi = pic_new.crop(
|
||
(scan_x_start, max(0, scan_y - 3), scan_x_end, min(pic_height, scan_y + 4))
|
||
).convert("RGB")
|
||
douyin_screenshot_manager.save_last_success(
|
||
detect_roi, operation_type="pixel_detect",
|
||
)
|
||
|
||
pic_rgb_full = pic_new.convert("RGB")
|
||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||
pic_rgb_full,
|
||
operation_type="pixel_detect",
|
||
picname="fudai_icon",
|
||
step="detected",
|
||
coords=(
|
||
scan_x_start, max(0, scan_y - 3),
|
||
scan_x_end, min(pic_height, scan_y + 4),
|
||
),
|
||
extra_info={
|
||
"detected_x": detected_x,
|
||
"detected_x_scaled": found_x,
|
||
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
|
||
"resolution": f"{rx}x{ry}",
|
||
"result": "success",
|
||
},
|
||
)
|
||
if debug_path:
|
||
try:
|
||
analyser._log_kv(
|
||
"[调试图像]",
|
||
"福袋图标检测成功保存完整截图",
|
||
path=debug_path,
|
||
detected_x=detected_x,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
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
|