From b1ee0e6b4efeb5ca07167b3f683d820a558299ca Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 22 May 2026 07:59:24 +0800 Subject: [PATCH] =?UTF-8?q?refactor(fudai):=20=E6=8F=90=E5=8F=96=20=5Fcapt?= =?UTF-8?q?ure=5Froi=5Fscreenshot=20=E5=92=8C=20=5Fmatch=5Ficon=5Ftemplate?= =?UTF-8?q?=20=E5=88=B0=20fudai=5Fimage=5Fhelpers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将 douyin_fudai.py 中两个图像处理工具方法(共 274 行)提取为 fudai_modules/fudai_image_helpers.py 模块级函数: - capture_roi_screenshot(analyser, ...) - match_icon_template(analyser, ...) 类内保留薄包装方法,调用签名不变,外部调用方(douyin_yanghao.py) 无需改动。 douyin_fudai.py: 4121 → 3861 行 (-260) 新增 fudai_image_helpers.py: 281 行 验证: - pytest 1013 passed - compile OK Co-Authored-By: Claude Opus 4.7 (1M context) --- douyin/core/douyin_fudai.py | 272 +---------------- .../core/fudai_modules/fudai_image_helpers.py | 281 ++++++++++++++++++ 2 files changed, 287 insertions(+), 266 deletions(-) create mode 100644 douyin/core/fudai_modules/fudai_image_helpers.py diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 715f7d8..3e0239c 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -854,278 +854,18 @@ class fudai_analyse: def _capture_roi_screenshot( self, label: str, sx: int, sy: int, size: int, screenshot_path: str = None ) -> str: - """捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。 + """捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。""" + from douyin.core.fudai_modules.fudai_image_helpers import capture_roi_screenshot - 返回 ROI 图片路径(绝对路径),失败返回空字符串。 - """ - try: - from douyin.core import path_config - - # use module-level `Image` - - # 确保有最新全图 - if screenshot_path is None: - try: - self.operation.get_screenshot(self.device_id, use_service=False) - except Exception: - pass - pic_path = path_config.get_screenshot_path() - else: - pic_path = screenshot_path - if not os.path.exists(pic_path): - return "" - - # 计算裁剪框(保证正方形,size 基于像素) - half = int(size // 2) - left = int(max(0, sx - half)) - top = int(max(0, sy - half)) - right = int(sx + half) - bottom = int(sy + half) - - # 以原子方式读取文件内容再由 PIL 解析,避免因文件替换/锁定导致的半写入问题 - import io - from PIL import UnidentifiedImageError # type: ignore[import] - - data = None - # 增强读取:多次尝试并在每次读到字节后用 PIL 验证,避免半写入/损坏 PNG 导致解析异常 - for attempt in range(6): - try: - try: - # 主动请求最新截图以尽量获得完整文件 - self.operation.get_screenshot(self.device_id, use_service=False) - except Exception: - pass - - if not os.path.exists(pic_path): - time.sleep(0.08) - continue - sz = os.path.getsize(pic_path) - if sz < 1024: - time.sleep(0.08) - continue - with open(pic_path, "rb") as f: - data = f.read() - if not data or not data.startswith(b"\x89PNG"): - data = None - time.sleep(0.08) - continue - # quick tail check - if b"IEND" not in data[-512:]: - data = None - time.sleep(0.08) - continue - - # 尝试由 PIL 快速验证(不加载像素,仅检查文件完整性) - try: - img_test = Image.open(io.BytesIO(data)) - img_test.verify() - except Exception: - data = None - time.sleep(0.08) - continue - - # 通过基本校验,退出重试循环 - break - except Exception: - data = None - time.sleep(0.08) - - if not data: - return "" - - try: - img = Image.open(io.BytesIO(data)) - img.load() - except UnidentifiedImageError: - return "" - except Exception: - # 如果首次解析仍然失败,尝试再获取一次截图并重试一次 - try: - try: - self.operation.get_screenshot(self.device_id, use_service=False) - except Exception: - pass - with open(pic_path, "rb") as f: - data2 = f.read() - if ( - data2 - and data2.startswith(b"\x89PNG") - and b"IEND" in data2[-512:] - ): - try: - img = Image.open(io.BytesIO(data2)) - img.load() - except Exception: - return "" - else: - return "" - except Exception: - return "" - w, h = img.size - # 修正边界 - left = max(0, min(left, w - 1)) - top = max(0, min(top, h - 1)) - right = max(1, min(right, w)) - bottom = max(1, min(bottom, h)) - - roi = img.crop((left, top, right, bottom)) - # 保存到 pic 目录,使用 label 区分 - out_dir = path_config.get_pic_dir() - os.makedirs(out_dir, exist_ok=True) - fname = ( - f"roi_{label}_{getattr(self, '_run_id', 'run')}_{int(time.time())}.png" - ) - out_path = os.path.join(out_dir, fname) - roi.save(out_path) - return out_path - except Exception: - try: - self._log_kv( - "截图", - "_capture_roi_screenshot 失败", - label=label, - sx=sx, - sy=sy, - size=size, - ) - except Exception: - pass - return "" + return capture_roi_screenshot(self, label, sx, sy, size, screenshot_path) def _match_icon_template( self, roi_path: str, template_path: str, threshold: float | None = None ) -> Tuple[bool, float]: - """对比 ROI 与模板,返回 (detected: bool, score: float)。 + """对比 ROI 与模板,返回 (detected: bool, score: float)。""" + from douyin.core.fudai_modules.fudai_image_helpers import match_icon_template - 使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。 - 如果提供 `threshold` 则使用该阈值判断匹配,否则回退到配置 `yanghao_icon_match_threshold`。 - 返回 (detected, score),若发生错误或文件缺失返回 (False, 0.0)。 - """ - try: - if not roi_path or not os.path.exists(roi_path): - return False, 0.0 - if not template_path or not os.path.exists(template_path): - return False, 0.0 - - # use module-level `Image` and `np` imports - - roi_img = Image.open(roi_path).convert("RGB") - tpl_img = Image.open(template_path).convert("RGB") - - rw, rh = roi_img.size - tw, th = tpl_img.size - # 若模板比 ROI 大,等比缩小模板 - if tw > rw or th > rh: - scale = min(rw / tw, rh / th, 1.0) - new_w = max(1, int(tw * scale)) - new_h = max(1, int(th * scale)) - tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS) - tw, th = tpl_img.size - - # 转为灰度数组 - roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32) - tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32) - - # 若模板尺寸等于 ROI,则直接计算相关系数 - if ( - roi_gray.shape[0] == tpl_gray.shape[0] - and roi_gray.shape[1] == tpl_gray.shape[1] - ): - A = roi_gray.flatten() - B = tpl_gray.flatten() - else: - # 若模板小于 ROI,则优先取 ROI 中心区域与模板尺寸一致的裁剪进行比对(更稳健), - # 如果中心裁剪分数很低再退回到滑动搜索(成本较高) - ih, iw = roi_gray.shape - th, tw = tpl_gray.shape - # 计算中心裁剪窗口 - if ih >= th and iw >= tw: - cy = ih // 2 - th // 2 - cx = iw // 2 - tw // 2 - cy = max(0, min(cy, ih - th)) - cx = max(0, min(cx, iw - tw)) - window = roi_gray[cy : cy + th, cx : cx + tw] - a = window.flatten() - b = tpl_gray.flatten() - a = a - a.mean() - b = b - b.mean() - denom = np.linalg.norm(a) * np.linalg.norm(b) - if denom > 1e-6: - score = float(np.dot(a, b) / denom) - else: - score = -1.0 - # 若中心裁剪得分足够好则直接返回 - if score >= 0.55: - used_thr = ( - float(threshold) - if threshold is not None - else float( - getattr(self, "yanghao_icon_match_threshold", 0.70) - or 0.70 - ) - ) - detected = score >= used_thr - return bool(detected), float(score) - - # 退回到滑动搜索(简易版),保留原有步长策略 - ih, iw = roi_gray.shape - th, tw = tpl_gray.shape - best = -1.0 - step_y = max(1, th // 6) - step_x = max(1, tw // 6) - for y in range(0, ih - th + 1, step_y): - for x in range(0, iw - tw + 1, step_x): - window = roi_gray[y : y + th, x : x + tw] - a = window.flatten() - b = tpl_gray.flatten() - a = a - a.mean() - b = b - b.mean() - denom = np.linalg.norm(a) * np.linalg.norm(b) - if denom <= 1e-6: - continue - score = float(np.dot(a, b) / denom) - if score > best: - best = score - if best < -0.5: - return False, 0.0 - score = float(best) - used_thr = ( - float(threshold) - if threshold is not None - else float( - getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70 - ) - ) - detected = score >= used_thr - return bool(detected), float(score) - - # 同尺寸直接计算相关系数 - A = roi_gray.flatten() - B = tpl_gray.flatten() - A = A - A.mean() - B = B - B.mean() - denom = np.linalg.norm(A) * np.linalg.norm(B) - if denom <= 1e-6: - return False, 0.0 - score = float(np.dot(A, B) / denom) - used_thr = ( - float(threshold) - if threshold is not None - else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70) - ) - detected = score >= used_thr - return bool(detected), float(score) - except Exception: - try: - self._log_kv( - "检测", - "_match_icon_template 异常", - roi_path=roi_path, - template_path=template_path, - ) - except Exception: - pass - return False, 0.0 + return match_icon_template(self, roi_path, template_path, threshold) def _check_in_live_room_by_icon( self, diff --git a/douyin/core/fudai_modules/fudai_image_helpers.py b/douyin/core/fudai_modules/fudai_image_helpers.py new file mode 100644 index 0000000..d825cc7 --- /dev/null +++ b/douyin/core/fudai_modules/fudai_image_helpers.py @@ -0,0 +1,281 @@ +"""福袋图像辅助函数 + +从 douyin_fudai.py 中提取的图像处理工具函数: +- capture_roi_screenshot:捕获 ROI 截图 +- match_icon_template:模板匹配 + +这两个函数原本是 fudai_analyse 类的方法 (_capture_roi_screenshot / _match_icon_template), +对 self 的依赖很轻,提取为模块级函数后,类内方法变为薄包装。 +""" +from __future__ import annotations + +import io +import os +import time +from typing import Tuple + +from PIL import Image, UnidentifiedImageError # type: ignore[import] +import numpy as np # type: ignore[import] + + +def capture_roi_screenshot( + analyser, + label: str, + sx: int, + sy: int, + size: int, + screenshot_path: str | None = None, +) -> str: + """捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。 + + 返回 ROI 图片路径(绝对路径),失败返回空字符串。 + """ + try: + from douyin.core import path_config + + if screenshot_path is None: + try: + analyser.operation.get_screenshot(analyser.device_id, use_service=False) + except Exception: + pass + pic_path = path_config.get_screenshot_path() + else: + pic_path = screenshot_path + if not os.path.exists(pic_path): + return "" + + half = int(size // 2) + left = int(max(0, sx - half)) + top = int(max(0, sy - half)) + right = int(sx + half) + bottom = int(sy + half) + + data = None + for attempt in range(6): + try: + try: + analyser.operation.get_screenshot( + analyser.device_id, use_service=False + ) + except Exception: + pass + + if not os.path.exists(pic_path): + time.sleep(0.08) + continue + sz = os.path.getsize(pic_path) + if sz < 1024: + time.sleep(0.08) + continue + with open(pic_path, "rb") as f: + data = f.read() + if not data or not data.startswith(b"\x89PNG"): + data = None + time.sleep(0.08) + continue + if b"IEND" not in data[-512:]: + data = None + time.sleep(0.08) + continue + + try: + img_test = Image.open(io.BytesIO(data)) + img_test.verify() + except Exception: + data = None + time.sleep(0.08) + continue + + break + except Exception: + data = None + time.sleep(0.08) + + if not data: + return "" + + try: + img = Image.open(io.BytesIO(data)) + img.load() + except UnidentifiedImageError: + return "" + except Exception: + try: + try: + analyser.operation.get_screenshot( + analyser.device_id, use_service=False + ) + except Exception: + pass + with open(pic_path, "rb") as f: + data2 = f.read() + if ( + data2 + and data2.startswith(b"\x89PNG") + and b"IEND" in data2[-512:] + ): + try: + img = Image.open(io.BytesIO(data2)) + img.load() + except Exception: + return "" + else: + return "" + except Exception: + return "" + w, h = img.size + left = max(0, min(left, w - 1)) + top = max(0, min(top, h - 1)) + right = max(1, min(right, w)) + bottom = max(1, min(bottom, h)) + + roi = img.crop((left, top, right, bottom)) + out_dir = path_config.get_pic_dir() + os.makedirs(out_dir, exist_ok=True) + fname = ( + f"roi_{label}_{getattr(analyser, '_run_id', 'run')}_{int(time.time())}.png" + ) + out_path = os.path.join(out_dir, fname) + roi.save(out_path) + return out_path + except Exception: + try: + analyser._log_kv( + "截图", + "_capture_roi_screenshot 失败", + label=label, + sx=sx, + sy=sy, + size=size, + ) + except Exception: + pass + return "" + + +def match_icon_template( + analyser, + roi_path: str, + template_path: str, + threshold: float | None = None, +) -> Tuple[bool, float]: + """对比 ROI 与模板,返回 (detected: bool, score: float)。 + + 使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。 + 如果提供 `threshold` 则使用该阈值判断匹配,否则回退到配置 `yanghao_icon_match_threshold`。 + 返回 (detected, score),若发生错误或文件缺失返回 (False, 0.0)。 + """ + try: + if not roi_path or not os.path.exists(roi_path): + return False, 0.0 + if not template_path or not os.path.exists(template_path): + return False, 0.0 + + roi_img = Image.open(roi_path).convert("RGB") + tpl_img = Image.open(template_path).convert("RGB") + + rw, rh = roi_img.size + tw, th = tpl_img.size + if tw > rw or th > rh: + scale = min(rw / tw, rh / th, 1.0) + new_w = max(1, int(tw * scale)) + new_h = max(1, int(th * scale)) + tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS) + tw, th = tpl_img.size + + roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32) + tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32) + + if ( + roi_gray.shape[0] == tpl_gray.shape[0] + and roi_gray.shape[1] == tpl_gray.shape[1] + ): + A = roi_gray.flatten() + B = tpl_gray.flatten() + else: + ih, iw = roi_gray.shape + th, tw = tpl_gray.shape + if ih >= th and iw >= tw: + cy = ih // 2 - th // 2 + cx = iw // 2 - tw // 2 + cy = max(0, min(cy, ih - th)) + cx = max(0, min(cx, iw - tw)) + window = roi_gray[cy : cy + th, cx : cx + tw] + a = window.flatten() + b = tpl_gray.flatten() + a = a - a.mean() + b = b - b.mean() + denom = np.linalg.norm(a) * np.linalg.norm(b) + if denom > 1e-6: + score = float(np.dot(a, b) / denom) + else: + score = -1.0 + if score >= 0.55: + used_thr = ( + float(threshold) + if threshold is not None + else float( + getattr(analyser, "yanghao_icon_match_threshold", 0.70) + or 0.70 + ) + ) + detected = score >= used_thr + return bool(detected), float(score) + + ih, iw = roi_gray.shape + th, tw = tpl_gray.shape + best = -1.0 + step_y = max(1, th // 6) + step_x = max(1, tw // 6) + for y in range(0, ih - th + 1, step_y): + for x in range(0, iw - tw + 1, step_x): + window = roi_gray[y : y + th, x : x + tw] + a = window.flatten() + b = tpl_gray.flatten() + a = a - a.mean() + b = b - b.mean() + denom = np.linalg.norm(a) * np.linalg.norm(b) + if denom <= 1e-6: + continue + score = float(np.dot(a, b) / denom) + if score > best: + best = score + if best < -0.5: + return False, 0.0 + score = float(best) + used_thr = ( + float(threshold) + if threshold is not None + else float( + getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70 + ) + ) + detected = score >= used_thr + return bool(detected), float(score) + + A = roi_gray.flatten() + B = tpl_gray.flatten() + A = A - A.mean() + B = B - B.mean() + denom = np.linalg.norm(A) * np.linalg.norm(B) + if denom <= 1e-6: + return False, 0.0 + score = float(np.dot(A, B) / denom) + used_thr = ( + float(threshold) + if threshold is not None + else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70) + ) + detected = score >= used_thr + return bool(detected), float(score) + except Exception: + try: + analyser._log_kv( + "检测", + "_match_icon_template 异常", + roi_path=roi_path, + template_path=template_path, + ) + except Exception: + pass + return False, 0.0