refactor(finder): 抽 numpy 加速扫描段到 finder_numpy_scan (937 → 811)

check_have_fudai_with_ready_screenshot L271-397 是"numpy 加速水平带扫描"
逻辑(126 行):ROI 裁剪 → RGB 颜色掩码 → 列聚合 → 从最优起始列向两侧
交替搜索第一个匹配列 → 写回 last_fudai_x。

抽到 douyin/detection/detection_pkg/finder_numpy_scan.py:
- scan_with_numpy(analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled)
  → (detected, detected_x)
- numpy ImportError / 异常时返回 (False, None),让 caller 走逐像素兜底

主 finder.py 替换为 7 行委托。

新增 8 个单元测试(用真实 PIL.Image + numpy 构造小图):
- 空图返回 False
- 整图目标色命中 + last_fudai_x 写回
- 仅在某段列有目标色,命中位置在该段
- y_pianyi_val 偏移正确传递到扫描带
- ROI 越界返回 False
- optimal_x_scaled 在命中区时优先返回该位置

1321 passed (+8)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-23 02:15:43 +08:00
1 parent 1514122981
commit 07cdd662c2
3 files changed
+333 -127

No files matched your search

+7 -127
View File
@@ -268,133 +268,13 @@ def check_have_fudai_with_ready_screenshot(
except Exception:
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
# numpy 加速扫描(性能优化,失败回退到逐像素扫描)
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
detected, _detected_x = scan_with_numpy(
analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled
)
if detected and _detected_x is not None:
detected_x = _detected_x
# numpy 未命中/不可用时回退到原始逐像素检查
if not detected:
@@ -0,0 +1,169 @@
"""douyin/detection/detection_pkg/finder_numpy_scan - numpy 加速福袋图标像素扫描
把 check_have_fudai_with_ready_screenshot 中"numpy 加速扫描水平带"段抽出来。
逻辑:在 ROI 内根据预设颜色范围生成像素掩码,按列聚合,从最优起始列向两侧
交替搜索第一个匹配列,命中即返回检测到的 x 坐标(1080 基准)。
入口:scan_with_numpy(analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled)
返回:(detected: bool, detected_x: Optional[int])
"""
from __future__ import annotations
import time
from typing import Any, Optional, Tuple
def scan_with_numpy(
analyser: Any,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
optimal_x_scaled: int,
) -> Tuple[bool, Optional[int]]:
"""numpy 加速扫描福袋图标的水平像素带。
Args:
analyser: 可读 last_fudai_x / 写 last_fudai_x / last_find_fudai_time
pic_new: PIL.Image,已加载的当前截图
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
y_pianyi_val: Y 偏移
optimal_x_scaled: 最优起始列(设备分辨率坐标)
Returns:
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标;
失败/异常返回 (False, None),由 caller 切换到逐像素扫描。
"""
try:
import numpy as _np
except (ImportError, ValueError, IndexError, AttributeError):
return False, None
width, height = pic_new.size
try:
# 计算检测区域,考虑分辨率缩放和偏移
# 将像素检测的扫描带左上角改为图片坐标 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 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] # 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 not valid_cols.any():
return False, None
# 从最优位置开始向左右两侧交替搜索
roi_width = x2 - x1
optimal_col = optimal_x_scaled - x1
optimal_col = max(0, min(optimal_col, roi_width - 1))
found_col: Optional[int] = 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
# 1080 基准坐标
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
+157
View File
@@ -0,0 +1,157 @@
"""douyin/detection/detection_pkg/finder_numpy_scan 单元测试。
scan_with_numpy 是个有较多 PIL/numpy 交互的纯函数。这里用真实的 PIL.Image
构造小图片做测试,避免 mock 太多。
"""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
try:
import numpy as np
from PIL import Image
except ImportError: # pragma: no cover
pytest.skip("numpy/PIL unavailable", allow_module_level=True)
def _mk_analyser():
a = MagicMock()
a.last_fudai_x = 0
a.last_find_fudai_time = 0.0
a._log_kv = MagicMock(return_value=None)
return a
def _make_solid_color_image(rgb, w=1080, h=2400):
"""生成纯色图片,方便控制 ROI 内是否有目标颜色。"""
return Image.new("RGB", (w, h), rgb)
def _make_image_with_target_band(target_rgb, x_start, x_end, y_target, w=1080, h=2400):
"""在 (x_start..x_end, y_target..y_target+5) 画上目标色,其它区域为黑。
可控的"目标在某些列出现"的图片,方便测试列扫描。
"""
img = Image.new("RGB", (w, h), (0, 0, 0))
arr = np.array(img)
arr[y_target:y_target + 5, x_start:x_end] = list(target_rgb)
return Image.fromarray(arr)
# 福袋图标颜色掩码:r ∈ [190, 206], g ∈ [173, 196], b ∈ [234, 250]
TARGET_RGB = (200, 185, 240)
NON_TARGET_RGB = (50, 50, 50)
class TestScanWithNumpy:
def test_blank_image_returns_false(self):
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
a = _mk_analyser()
pic = _make_solid_color_image(NON_TARGET_RGB)
detected, x = scan_with_numpy(a, pic, rx=1080, ry=2400, y_pianyi_val=0, optimal_x_scaled=200)
assert detected is False
assert x is None
def test_solid_target_color_detects(self):
"""整图都是目标色 → ROI 全部命中 → 应该检测到。"""
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
a = _mk_analyser()
pic = _make_solid_color_image(TARGET_RGB)
detected, x = scan_with_numpy(
a, pic, rx=1080, ry=2400, y_pianyi_val=0, optimal_x_scaled=200
)
assert detected is True
assert x is not None
# optimal_x_scaled=200 落在 ROI 内(157..410),命中应该就在最优位置
assert 157 <= x <= 410
def test_target_in_specific_band(self):
"""只在某段列有目标色 → 命中位置应在该段内。"""
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
a = _mk_analyser()
# ROI Y 范围:354 - 3 = 351..361
# 在 x ∈ [200, 250], y=355 处画目标色
pic = _make_image_with_target_band(
TARGET_RGB, x_start=200, x_end=250, y_target=353
)
detected, x = scan_with_numpy(
a, pic, rx=1080, ry=2400, y_pianyi_val=0, optimal_x_scaled=220
)
assert detected is True
# x 应落在 200..250 范围内(1080 基准坐标)
assert 200 <= x <= 250
def test_writes_back_last_fudai_x_on_hit(self):
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
a = _mk_analyser()
a.last_fudai_x = 0 # 起初没有
pic = _make_solid_color_image(TARGET_RGB)
detected, x = scan_with_numpy(
a, pic, rx=1080, ry=2400, y_pianyi_val=0, optimal_x_scaled=200
)
assert detected is True
assert a.last_fudai_x == x # 命中后写回
def test_does_not_write_back_on_miss(self):
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
a = _mk_analyser()
a.last_fudai_x = 0
pic = _make_solid_color_image(NON_TARGET_RGB)
detected, _ = scan_with_numpy(
a, pic, rx=1080, ry=2400, y_pianyi_val=0, optimal_x_scaled=200
)
assert detected is False
assert a.last_fudai_x == 0 # 未命中不写
def test_y_offset_shifts_scan_band(self):
"""y_pianyi_val 偏移应使扫描带也偏移;目标色画到偏移后位置才命中。"""
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
a = _mk_analyser()
offset = 100
# ROI 中心 y0 = 354 + 100 = 454,所以 y_top = 451..461
pic = _make_image_with_target_band(
TARGET_RGB, x_start=200, x_end=250, y_target=453
)
detected, x = scan_with_numpy(
a, pic, rx=1080, ry=2400, y_pianyi_val=offset, optimal_x_scaled=220
)
assert detected is True
def test_invalid_roi_returns_false(self):
"""rx 极大导致 x1 >= x2 → ROI 无效 → False。"""
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
a = _mk_analyser()
pic = _make_solid_color_image(TARGET_RGB, w=10, h=10)
# rx=10000 让 157*10000//1080 越界
detected, _ = scan_with_numpy(
a, pic, rx=10000, ry=2400, y_pianyi_val=0, optimal_x_scaled=200
)
# x1 = max(0, 157*10000//1080) = 1453,x2 = min(10, 410*10000//1080) = 10
# x1 > x2 → 返回 False
assert detected is False
def test_optimal_x_search_prefers_optimal_location(self):
"""optimal_x_scaled 在命中区域内时,命中应该正好就在那里。"""
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
a = _mk_analyser()
# 在 x ∈ [200, 300] 都画上目标色
pic = _make_image_with_target_band(
TARGET_RGB, x_start=200, x_end=300, y_target=353
)
# optimal_x_scaled=250(恰在中间)
detected, x = scan_with_numpy(
a, pic, rx=1080, ry=2400, y_pianyi_val=0, optimal_x_scaled=250
)
assert detected is True
# 因为 optimal_col 一定命中,x 应该非常接近 250
assert 245 <= x <= 255