from __future__ import annotations """ 截图与图像处理模块 ================== 职责:截图、图像处理和坐标转换 - 截图裁剪 - 保存步骤截图 - 坐标缩放 """ import os import shutil from typing import Any, Tuple class ScreenshotHandler: """截图处理器:统一管理截图操作""" @staticmethod # type: ignore[misc] def cut_pic( analyser: Any, x_top: int = 1, y_top: int = 1, x_bottom: int = 2, y_bottom: int = 2, target: str = "", cut_pic_name: str = "", y_pianyi: int = 0, ) -> None: """裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。 参数: analyser: 分析器对象 x_top: 顶部X坐标(基准1080) y_top: 顶部Y坐标(基准2400) x_bottom: 底部X坐标(基准1080) y_bottom: 底部Y坐标(基准2400) target: 目标路径 cut_pic_name: 裁剪图片名称 y_pianyi: Y轴偏移 """ try: x1 = x_top * analyser.resolution_ratio_x // 1080 y1 = y_top * analyser.resolution_ratio_y // 2400 + int(y_pianyi or 0) x2 = x_bottom * analyser.resolution_ratio_x // 1080 y2 = y_bottom * analyser.resolution_ratio_y // 2400 + int(y_pianyi or 0) analyser.operation.cut_pic((x1, y1), (x2, y2), target, cut_pic_name) except Exception as e: try: analyser._log_kv( # type: ignore[attr-defined] "截图", "cut_pic 失败", error=str(e), x_top=x_top, y_top=y_top, x_bottom=x_bottom, y_bottom=y_bottom, y_pianyi=y_pianyi, log_type="SCREENSHOT", ) except Exception: pass @staticmethod # type: ignore[misc] def scale_from_base(analyser: Any, base_x: int, base_y: int) -> Tuple[int, int]: """将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。 参数: analyser: 分析器对象 base_x: 基准X坐标(1080基准) base_y: 基准Y坐标(2400基准) 返回: (scaled_x, scaled_y) 缩放后的坐标 """ try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) y_off = int(getattr(analyser, "y_pianyi", 0) or 0) sx = int(base_x * rx // 1080) sy = int(base_y * ry // 2400) + y_off return sx, sy except Exception: try: return int(base_x), int(base_y) except Exception: return 0, 0 @staticmethod # type: ignore[misc] def save_step_screenshot(analyser: Any, label: str) -> None: """保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试使用。 参数: analyser: 分析器对象 label: 标签(用于文件名) """ try: base_dir = os.path.dirname(__file__) pic_dir = os.path.join(base_dir, "pic") # 确保有最新截图 try: analyser.operation.get_screenshot(analyser.device_id, use_service=False) except Exception: pass src = os.path.join(pic_dir, "screenshot.png") if not os.path.exists(src): return steps_dir = os.path.join(pic_dir, "steps") os.makedirs(steps_dir, exist_ok=True) fname = ( f"{getattr(analyser, '_run_id', 'run')}_" f"{getattr(analyser, '_log_seq', 0):04d}_{label}.png" ) dst = os.path.join(steps_dir, fname) try: shutil.copy(src, dst) except Exception: # 最后降级为重命名保存 try: shutil.copy(src, dst) except Exception: pass except Exception: pass