Files
douyin_guaji-main/douyin/detection/detection_pkg/finder_pixel_scan.py
T
CodexandClaude Opus 4.7 ab846dae0f refactor(finder): 抽逐像素兜底扫描到 finder_pixel_scan (817 → 635)
check_have_fudai_with_ready_screenshot L279-461 是 numpy 失败时的逐像素
兜底(183 行):optimal_x 从历史 / 默认热区中心选起 → 检查 5 个 y 偏移
(0/±1/±2)→ 每行从 optimal 向两侧交替搜索 → 最后从左到右兜底。

抽到 douyin/detection/detection_pkg/finder_pixel_scan.py:
- scan_pixel_by_pixel(analyser, pic_new, rx, ry, y_pianyi_val) → (detected, x)
- _is_target_pixel / _safe_check_pixel / _pick_optimal_x / _search_along_y
  4 个独立纯函数,每个职责单一

颜色范围常量与 finder_numpy_scan 对齐(_R_MIN/_MAX 等)。

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

新增 15 个单元测试覆盖:
- _is_target_pixel 边界 / _safe_check_pixel 异常兜底
- _pick_optimal_x 历史命中/越界/无历史 3 种路径
- scan_pixel_by_pixel 主路径成功 / y 偏移 / 越界失败 / pic 异常兜底

1336 passed (+15)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:20:25 +08:00

206 lines
6.9 KiB
Python

"""douyin/detection/detection_pkg/finder_pixel_scan - 逐像素福袋图标扫描兜底
当 numpy 加速扫描没找到时,回退到逐像素遍历。逻辑与 numpy 版相似但
使用 PIL.Image.load() 提供的像素访问,性能较慢但兼容性最好。
入口:scan_pixel_by_pixel(analyser, pic_new, rx, ry, y_pianyi_val)
返回:(detected: bool, detected_x: Optional[int])
颜色范围与 finder_numpy_scan 一致:r ∈ [190, 206], g ∈ [173, 196], b ∈ [234, 250]。
"""
from __future__ import annotations
import time
from typing import Any, Optional, Tuple
# 福袋图标主色范围(与 finder_numpy_scan 共享)
_R_MIN, _R_MAX = 190, 206
_G_MIN, _G_MAX = 173, 196
_B_MIN, _B_MAX = 234, 250
def _is_target_pixel(px) -> bool:
"""检查像素是否落在目标颜色范围内。"""
if not (isinstance(px, tuple) and len(px) >= 3):
return False
r, g, b = px[0], px[1], px[2]
return _R_MIN <= r <= _R_MAX and _G_MIN <= g <= _G_MAX and _B_MIN <= b <= _B_MAX
def _safe_check_pixel(pix, x: int, y: int) -> bool:
"""读 pix[x, y] 后检查是否目标颜色,越界/类型错误时返回 False。"""
try:
return _is_target_pixel(pix[x, y])
except (IndexError, TypeError):
return False
def _pick_optimal_x(analyser, scan_x_start: int, scan_x_end: int, rx: int) -> int:
"""选择本次扫描的最优起始列:优先用历史 last_fudai_x,否则默认热区中心。"""
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
):
return last_fudai_x * rx // 1080
except Exception:
pass
# 默认最优位置:最热门区域中心(98-240 的中心,约 169)
return 169 * rx // 1080
def _search_along_y(
pix,
scan_x_start: int,
scan_x_end: int,
optimal_x_scaled: int,
check_y: int,
) -> Optional[int]:
"""在指定 y 行上找第一个目标色像素的 x 坐标。
搜索顺序:optimal_x → 向两侧交替搜索 → 最后从左到右兜底。
"""
# 1. 先检查最优位置本身
if _safe_check_pixel(pix, optimal_x_scaled, check_y):
return optimal_x_scaled
# 2. 向左右两侧交替搜索
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 and _safe_check_pixel(pix, right_x, check_y):
return right_x
left_x = optimal_x_scaled - offset
if left_x >= scan_x_start and _safe_check_pixel(pix, left_x, check_y):
return left_x
# 3. 最后从左到右扫一遍兜底
for x_scaled in range(scan_x_start, scan_x_end):
if _safe_check_pixel(pix, x_scaled, check_y):
return x_scaled
return None
def scan_pixel_by_pixel(
analyser: Any,
pic_new,
rx: int,
ry: int,
y_pianyi_val: 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 偏移
Returns:
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标。
"""
detected = False
detected_x: Optional[int] = None
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
optimal_x_scaled = _pick_optimal_x(analyser, scan_x_start, scan_x_end, rx)
# 确保最优位置在搜索范围内
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 = _search_along_y(
pix, scan_x_start, scan_x_end, optimal_x_scaled, check_y
)
if found_x is None:
continue
# 命中:转换回 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 循环
except Exception:
# 像素检测失败,记录但不影响主流程
pass
return detected, detected_x