refactor(detection): 拆出 finder.py numpy + 逐像素扫描(719→428,-291 行)

把 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>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-22 04:59:38 +08:00
1 parent a391c21f47
commit d24bc85902
3 files changed
+465 -308

No files matched your search

+17 -308
View File
@@ -14,7 +14,11 @@ from typing import Any
from PIL import Image
from ._common import _ensure_detection_cache
from .template_match_helpers import template_match_fallback
from .template_match_helpers import (
numpy_pixel_scan,
per_pixel_scan_fallback,
template_match_fallback,
)
def check_have_fudai_with_ready_screenshot(
@@ -270,316 +274,21 @@ def check_have_fudai_with_ready_screenshot(
pass
# 先尝试 numpy 加速扫描水平带(性能优化:批量处理)
try:
import numpy as _np
# 计算检测区域,考虑分辨率缩放和偏移
# 将像素检测的扫描带左上角改为图片坐标 x=157, y=354(右下不变)
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 x1 < x2 and y_top < y_bottom:
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:
r = arr[:, :, 0] # type: ignore[index]
g = arr[:, :, 1] # type: ignore[index]
b = arr[:, :, 2] # type: ignore[index]
# 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度)
# 原来的范围:R[193-203], G[176-193], B[237-247]
# 优化后:适度放宽范围,但保持中心值权重
mask_center = (r >= 190) & (r <= 206) & (g >= 173) & (g <= 196) & (b >= 234) & (b <= 250) # type: ignore[operator]
# 速度优化:使用更宽松的预筛选,减少计算量
mask = mask_center
# 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判)
cols = _np.sum(mask, axis=0)
# 至少需要2个像素匹配(避免单个噪点误判)
valid_cols = cols >= 2
if valid_cols.any():
# 优化:从最优位置开始向左右两侧搜索
roi_width = x2 - x1
optimal_col = optimal_x_scaled - x1 # 转换为ROI内的列索引
optimal_col = max(0, min(optimal_col, 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
# 计算检测到的x坐标:转换为1080基准坐标,确保精度
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
detected = True
# 保存找到的位置作为下次的最优位置
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
except (ImportError, ValueError, IndexError, AttributeError):
# numpy不可用或计算错误,回退到逐像素检测
detected = False
np_detected, np_x = numpy_pixel_scan(
analyser, pic_new, rx, ry, width, height, y_pianyi_val, optimal_x_scaled,
)
if np_detected:
detected = True
detected_x = np_x
# numpy 未命中/不可用时回退到原始逐像素检查
if not detected:
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:
# 尝试获取上次找到的福袋位置(1080基准)
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:
# 使用默认最优位置:最热门区域中心(98-240的中心,约169)
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)
)
# 确保y坐标在有效范围内
if 0 <= scan_y < pic_height:
# 精度优化:同时检查上下几行像素,提高检测准确性
for offset_y in [0, -1, 1, -2, 2]: # 检查当前行及上下2行
check_y = scan_y + offset_y
if not (0 <= check_y < pic_height):
continue
# 优化:从最优位置开始向左右两侧搜索
found_x = None
search_range = max(
optimal_x_scaled - scan_x_start,
scan_x_end - optimal_x_scaled,
)
# 先检查最优位置本身
try:
px = pix[optimal_x_scaled, check_y]
if isinstance(px, tuple) and len(px) >= 3:
if (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
found_x = optimal_x_scaled
except (IndexError, TypeError):
pass
# 如果最优位置没找到,向左右两侧交替搜索
if found_x is None:
for offset in range(1, search_range + 1):
# 先检查右侧
right_x = optimal_x_scaled + offset
if right_x < scan_x_end:
try:
px = pix[right_x, check_y]
if isinstance(px, tuple) and len(px) >= 3:
if (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
found_x = right_x
break
except (IndexError, TypeError):
continue
# 再检查左侧
left_x = optimal_x_scaled - offset
if left_x >= scan_x_start:
try:
px = pix[left_x, check_y]
if isinstance(px, tuple) and len(px) >= 3:
if (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
found_x = left_x
break
except (IndexError, TypeError):
continue
# 如果还是没找到,回退到原来的方法(从左到右)
if found_x is None:
for x_scaled in range(scan_x_start, scan_x_end):
try:
px = pix[x_scaled, check_y]
if isinstance(px, tuple) and len(px) >= 3:
if (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
found_x = x_scaled
break
except (IndexError, TypeError):
continue
if found_x is not None:
# 转换回1080基准坐标
detected_x = int(found_x * 1080.0 / max(1, rx))
detected = True
# 保存找到的位置作为下次的最优位置
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
# 双截图记录:保存成功识别存档截图
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
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
break # 找到后退出offset_y循环
if detected:
break # 找到后退出外层循环
except Exception:
# 像素检测失败,记录但不影响主流程
pass
pp_detected, pp_x = per_pixel_scan_fallback(
analyser, pic_new, rx, ry, y_pianyi_val,
)
if pp_detected:
detected = True
detected_x = pp_x
# 像素检测未命中时,使用模板匹配作为兜底
if not detected or detected_x is None:
@@ -2,6 +2,8 @@
把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"逻辑(226 行)
抽出来,便于独立测试与维护。
同时包含 numpy 加速像素扫描 + 逐像素扫描兜底的辅助函数。
"""
from __future__ import annotations
@@ -10,6 +12,304 @@ 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)
+148
View File
@@ -137,3 +137,151 @@ def test_template_match_full_pipeline_perfect_match(tmp_path, monkeypatch):
# 检测到的 x 应当在嵌入位置附近(embed_x + tw//2 = 200 + 15 = 215,1080 基准下相同)
assert x is not None
assert abs(x - (embed_x + 15)) <= 5
# ---- numpy_pixel_scan ---- #
def test_numpy_pixel_scan_no_match(tmp_path):
"""全黑图像 → numpy 扫描不会命中目标颜色范围"""
pytest.importorskip("numpy")
import numpy as np
from PIL import Image
a = _make_analyser()
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.numpy_pixel_scan(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0,
optimal_x_scaled=169,
)
assert detected is False
assert x is None
def test_numpy_pixel_scan_with_match(tmp_path):
"""构造目标颜色 → numpy 扫描命中"""
pytest.importorskip("numpy")
import numpy as np
from PIL import Image
a = _make_analyser()
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255
# 目标颜色 R=200, G=185, B=240(在范围内:R[190-206], G[173-196], B[234-250])
# 在搜索区域 X=157-410, Y=354 附近放一列像素(每列至少 2 个像素,valid_cols >= 2)
target_x = 250
pic_arr[353:355, target_x, 0] = 200
pic_arr[353:355, target_x, 1] = 185
pic_arr[353:355, target_x, 2] = 240
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.numpy_pixel_scan(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0,
optimal_x_scaled=target_x,
)
assert detected is True
assert x == target_x
def test_numpy_pixel_scan_invalid_roi():
"""搜索区域无效(width < 157)→ 直接返回 False"""
a = _make_analyser()
pic = MagicMock()
detected, x = h.numpy_pixel_scan(
a, pic, rx=1080, ry=2400,
width=100, height=2400, y_pianyi_val=0, # width < 157
optimal_x_scaled=169,
)
assert detected is False
# ---- per_pixel_scan_fallback ---- #
def test_per_pixel_scan_no_match():
"""全白图 → 像素逐行扫描找不到目标颜色"""
import numpy as np
from PIL import Image
a = _make_analyser()
pic_arr = np.full((2400, 1080, 4), 255, dtype=np.uint8)
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.per_pixel_scan_fallback(
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
)
assert detected is False
assert x is None
def test_per_pixel_scan_with_match():
"""构造目标像素 → 逐行扫描命中"""
import numpy as np
from PIL import Image
a = _make_analyser()
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255
# 在 scan_y=403, scan_x=200 处放目标像素
pic_arr[403, 200] = (200, 185, 240, 255)
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.per_pixel_scan_fallback(
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
)
assert detected is True
assert x == 200
def test_per_pixel_scan_uses_last_fudai_x():
"""analyser.last_fudai_x 设置时,从该位置开始搜索"""
import numpy as np
from PIL import Image
a = _make_analyser()
a.last_fudai_x = 250
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255
pic_arr[403, 250] = (200, 185, 240, 255)
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.per_pixel_scan_fallback(
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
)
assert detected is True
assert x == 250
def test_per_pixel_scan_swallows_exception():
"""pic.load() 抛错时不应崩"""
a = _make_analyser()
bad_pic = MagicMock()
bad_pic.load.side_effect = RuntimeError("boom")
detected, x = h.per_pixel_scan_fallback(
a, bad_pic, rx=1080, ry=2400, y_pianyi_val=0,
)
assert detected is False
assert x is None
# ---- _is_target_pixel ---- #
def test_is_target_pixel_in_range():
assert h._is_target_pixel((200, 185, 240)) is True
assert h._is_target_pixel((190, 173, 234)) is True
assert h._is_target_pixel((206, 196, 250)) is True
def test_is_target_pixel_out_of_range():
assert h._is_target_pixel((189, 185, 240)) is False
assert h._is_target_pixel((200, 197, 240)) is False
assert h._is_target_pixel((200, 185, 233)) is False
def test_is_target_pixel_non_tuple():
assert h._is_target_pixel(None) is False
assert h._is_target_pixel((100,)) is False # 长度不够
assert h._is_target_pixel("not_tuple") is False