From 4642a00b8d93dc8986ad8569585377048e30732c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=A5=E4=B8=80=E4=B8=80?= <1204244136@qq.com> Date: Sat, 19 Sep 2026 14:04:24 +0800 Subject: [PATCH 1/2] fix(vision): align screenshots with controller coordinates Default both controllers to a 720-pixel short side, preserve screenshot dimensions unless resizing is explicit, and remove duplicate OCR ROI offsets. Add configurable controller resolution, optional screenshot coordinate transforms, migration documentation, and native regression tests using synthetic images. --- CLAUDE.md | 4 +- CLAUDE_CN.md | 4 +- README.md | 26 +++ README_EN.md | 30 ++++ maa_mcp/adb.py | 21 ++- maa_mcp/control.py | 8 +- maa_mcp/core.py | 6 + maa_mcp/vision.py | 105 ++++++++---- maa_mcp/win32.py | 18 +- tests/test_coordinates.py | 350 ++++++++++++++++++++++++++++++++++++++ tests/test_vision.py | 20 +-- 11 files changed, 537 insertions(+), 55 deletions(-) create mode 100644 tests/test_coordinates.py diff --git a/CLAUDE.md b/CLAUDE.md index 6642d73..fb79666 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -162,7 +162,9 @@ Before drawing any conclusion from a tool call, verify: ### MaaMCP tool behavior notes (project-specific) -- __`ocr` / `screencap` accept `region=(x,y,w,h)`__ — small-region OCR is 4–8× faster, coords auto-compensated to original screen via maafw `JOCR(roi=..., roi_offset=...)` (no manual Python crop+offset needed). See commit `ea4b4bd` for the perf data. +- __`ocr` / `screencap` accept `region=(x,y,w,h)`__: regions use full controller screenshot coordinates. OCR uses `JOCR(roi=...)`; the framework restores the origin automatically. Do not repeat roi in roi_offset. +- __Shared coordinate basis__: Win32/ADB default to a 720-pixel short side. Connection parameter `target_short_side` accepts another positive integer or `None` (native size). `screencap` defaults to `resolution=None`, preserving controller image dimensions. OCR, actions, and Pipelines use that controller's coordinates. Non-720 modes do not automatically adapt existing 720p templates or ROIs. +- __Locating targets after cropping/resizing__: `screencap(..., include_metadata=True)` returns `path`, `coordinate_size`, `image_size`, and `image_to_controller`. Map image point `(u,v)` to `(u*sx+ox,v*sy+oy)` and round before acting. The default return remains a path string; metadata's `path` can be passed to `save_captured_image`. - __Win32 `click` on Chromium/Electron windows can silent-fail__ — PostMessage mouse events are dropped, API returns True but no visual change. Keyboard events (`post_input_text`, `post_key_*`) still work because Chrome's keyboard handler is more lenient. Tool description has the full caveat. - __`input_text` requires target focus__ — it sends keyboard events to the focused element. If `click` failed to focus, `input_text` lands elsewhere. Sequence: `click(target)` → `input_text(text)` in __immediate succession__, no `screencap/ocr` between. - __Controller has a lifecycle__ — system cross-day, Chrome restart, or sleep/wake invalidates `controller_id`. Symptom: all operations return `None`/`False` silently. Fix: re-call `find_window_list()` + `connect_window()`. diff --git a/CLAUDE_CN.md b/CLAUDE_CN.md index 5142779..860473c 100644 --- a/CLAUDE_CN.md +++ b/CLAUDE_CN.md @@ -161,7 +161,9 @@ OCR 模型和截图存储在平台特定的目录中: ### MaaMCP 工具行为注记(项目特定) -- __`ocr` / `screencap` 支持 `region=(x,y,w,h)`__——小区域 OCR 提速 4–8×,坐标由 maafw `JOCR(roi=..., roi_offset=...)` 自动补偿(不用 Python 侧手写 crop+offset)。性能数据见 commit `ea4b4bd`。 +- __`ocr` / `screencap` 支持 `region=(x,y,w,h)`__:region 使用控制器完整截图坐标。OCR 使用 `JOCR(roi=...)`,框架自动补回原点;不要将 roi 重复赋给 roi_offset。 +- __统一坐标基准__:Win32/ADB 默认短边 720,连接参数 `target_short_side` 可选其他正整数或 `None`(原尺寸)。`screencap` 默认 `resolution=None`,保留控制器截图尺寸;OCR、动作和 Pipeline 坐标均服从该控制器。非 720 模式不会自动适配既有 720p 模板及 ROI。 +- __裁图/缩放后的定位__:`screencap(..., include_metadata=True)` 返回 `path`、`coordinate_size`、`image_size` 和 `image_to_controller`。图中 `(u,v)` 换算为 `(u*sx+ox,v*sy+oy)` 后取整再操作。默认仍返回路径字符串;元数据中的 `path` 可直接传给 `save_captured_image`。 - __Win32 `click` 对 Chromium/Electron 窗口可能静默失效__——PostMessage 鼠标消息被 Chromium 丢,API 返回 True 但界面无变化。键盘消息(`post_input_text` / `post_key_*`)仍能正常投递(Chrome 内部对键盘消息更宽松)。完整说明在工具描述里。 - __`input_text` 需要目标已聚焦__——它把字符投到当前焦点元素。`click` 失败没建立焦点的话,`input_text` 会投到错误位置。正确顺序:`click(target)` → `input_text(text)` __紧接__,中间不夹 screencap/ocr。 - __Controller 有生命周期__——系统跨天 / Chrome 重启 / 休眠唤醒后,`controller_id` 失效。症状:所有操作静默返回 None/False。处理:重新 `find_window_list()` + `connect_window()`。 diff --git a/README.md b/README.md index cd38930..19bb914 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,32 @@ Talk is cheap, 请看: **[🎞️ Bilibili 视频演示](https://www.bilibili.co - `ocr` - 光学字符识别(高效,推荐优先使用) - `screencap` - 屏幕截图(按需使用,token 开销大) +#### 截图与坐标约定 + +Win32 和 ADB 连接默认使用 `target_short_side=720`,保持画面比例。OCR 的 `region`、 +返回框、点击、滑动和 Pipeline 均使用该控制器的完整截图坐标,不一定是设备物理坐标。 +`screencap` 默认 `resolution=None`,不再额外缩放,整图坐标可直接用于操作。 + +连接时可传 `target_short_side=1080` 等正整数,或传 `None` 使用原尺寸。该选项会改变 +整个控制器的坐标基准,模板和 Pipeline ROI 必须使用匹配的尺度;现有 720p 资源应保留 +默认连接设置。依赖旧版 Win32 1080p 坐标的调用方可显式选择 `1080`。 + +`screencap` 默认仍返回路径字符串。裁图或显式设置 `resolution` 后需要定位操作时, +传入 `include_metadata=True`,返回以下信息: + +| 字段 | 含义 | +| --- | --- | +| `path` | 图像绝对路径,也可传给 `save_captured_image` | +| `controller_id` / `coordinate_system` | 所属控制器及坐标空间(`controller`) | +| `coordinate_size` | 控制器完整截图 `[宽, 高]` | +| `image_size` | 保存图像 `[宽, 高]` | +| `image_to_controller.scale` | 图像到控制器的 `[sx, sy]` 比例 | +| `image_to_controller.offset` | 实际裁剪原点在控制器空间中的 `[ox, oy]` | + +图中点 `(u, v)` 应换算为 `(round(u*sx+ox), round(v*sy+oy))` 再用于点击。 +变换包含实际缩放尺寸、取整和裁剪边界修正,只对应本次截图;窗口大小或布局变化后应重新截图。 +显式 `resolution` 只影响保存图像,不改变控制器坐标,也不能恢复之前下采样丢失的细节。 + ### 🎮 设备控制 - `click` - 点击指定坐标(支持多触点/鼠标按键选择、长按) diff --git a/README_EN.md b/README_EN.md index d437838..319381c 100644 --- a/README_EN.md +++ b/README_EN.md @@ -51,6 +51,36 @@ Talk is cheap, see: **[🎞️ Bilibili Video Demo](https://www.bilibili.com/vid - `ocr` - Optical Character Recognition (efficient, recommended for priority use, OCR model auto-downloads on first use) - `screencap` - Screenshot capture (use as needed, high token cost) +#### Screenshot Coordinates + +Win32 and ADB connections default to `target_short_side=720`, preserving aspect ratio. +OCR regions and boxes, clicks, swipes, and Pipelines all use the controller's full screenshot +coordinates, which may differ from physical device coordinates. `screencap` now defaults to +`resolution=None`, preserving that image size so full-image coordinates can be used directly. + +Pass a positive `target_short_side`, such as `1080`, when connecting, or `None` for native size. +This changes the coordinate basis of the entire controller: templates and Pipeline ROIs must +use the corresponding scale. Keep the default for existing 720p resources. Callers that rely +on the previous Win32 1080p coordinates can explicitly select `1080`. + +`screencap` still returns a path string by default. When locating targets in cropped or explicitly +resized images, pass `include_metadata=True` to receive: + +| Field | Meaning | +| --- | --- | +| `path` | Absolute image path, also accepted by `save_captured_image` | +| `controller_id` / `coordinate_system` | Owning controller and coordinate space (`controller`) | +| `coordinate_size` | Full controller screenshot `[width, height]` | +| `image_size` | Saved image `[width, height]` | +| `image_to_controller.scale` | Image-to-controller scale `[sx, sy]` | +| `image_to_controller.offset` | Actual crop origin in controller coordinates `[ox, oy]` | + +Map an image point `(u, v)` to `(round(u*sx+ox), round(v*sy+oy))` before clicking. +The transform includes actual resized dimensions, rounding, and crop boundary clamping. It only +describes this capture; take another screenshot after the window size or layout changes. +Explicit `resolution` only affects the saved image, not controller coordinates, and cannot +restore detail lost in an earlier downsampling step. + ### 🎮 Device Control - `click` - Click at coordinates (supports multi-touch/mouse button selection, long press) diff --git a/maa_mcp/adb.py b/maa_mcp/adb.py index 7fbe35d..8a4ae83 100644 --- a/maa_mcp/adb.py +++ b/maa_mcp/adb.py @@ -40,6 +40,9 @@ def find_adb_device_list() -> list[str]: 参数: - device_name: 目标设备名称,需通过 find_adb_device_list() 获取 + - target_short_side: 控制器截图短边,默认 720;可设为其他正整数。 + 传 None 使用原始尺寸。OCR、动作和 Pipeline 均使用该控制器的截图坐标, + 非 720 模式需要匹配的模板及 ROI。 返回值: - 成功:返回控制器 ID(字符串),用于后续所有设备操作 @@ -49,7 +52,13 @@ def find_adb_device_list() -> list[str]: 控制器 ID 将用于后续的点击、滑动、截图等操作,请妥善保存。 """, ) -def connect_adb_device(device_name: str) -> Optional[str]: +def connect_adb_device( + device_name: str, target_short_side: Optional[int] = 720 +) -> Optional[str]: + if target_short_side is not None and ( + type(target_short_side) is not int or target_short_side <= 0 + ): + raise ValueError("target_short_side must be a positive integer or None") device = object_registry.get(device_name) if not device: return None @@ -61,9 +70,12 @@ def connect_adb_device(device_name: str) -> Optional[str]: device.input_methods, device.config, ) - # 设置默认截图短边为 720p - # 手机上文字/图标通常较大,不需要太高清 - adb_controller.set_screenshot_target_short_side(720) + if target_short_side is None: + configured = adb_controller.set_screenshot_use_raw_size(True) + else: + configured = adb_controller.set_screenshot_target_short_side(target_short_side) + if not configured: + return None if not adb_controller.post_connection().wait().succeeded: return None @@ -75,6 +87,7 @@ def connect_adb_device(device_name: str) -> Optional[str]: "screencap_methods": device.screencap_methods, "input_methods": device.input_methods, "config": device.config, + "target_short_side": target_short_side, } controller_info_registry[controller_id] = ControllerInfo( diff --git a/maa_mcp/control.py b/maa_mcp/control.py index e8fb676..cdc634e 100644 --- a/maa_mcp/control.py +++ b/maa_mcp/control.py @@ -23,7 +23,9 @@ - 失败:返回 False 说明: - 坐标系统以屏幕左上角为原点 (0, 0),X 轴向右,Y 轴向下。 + 坐标使用控制器完整截图空间,以左上角为原点 (0, 0),X 轴向右,Y 轴向下。 + 默认全屏 screencap 和 OCR 返回框可直接用于点击。显式缩放或裁剪的截图 + 坐标需先换算回完整截图空间;设备物理分辨率可能与该空间不同。 重要提示: - 返回 True 不代表"视觉上生效"。Win32 控制器对 Chromium/Electron @@ -67,7 +69,7 @@ def click( - 失败:返回 False 说明: - 坐标系统以屏幕左上角为原点 (0, 0),X 轴向右,Y 轴向下。 + 坐标使用控制器完整截图空间,与默认全屏 screencap、OCR 和 click 一致。 """, ) def double_click( @@ -118,7 +120,7 @@ def double_click( - 失败:返回 False 说明: - - 坐标系统以屏幕左上角为原点 (0, 0) + - 坐标使用控制器完整截图空间,与默认全屏 screencap、OCR 和 click 一致 - duration 参数控制滑动速度,数值越大滑动越慢 - 起点、终点坐标由 AI 根据当前 OCR 识别结果和场景自行计算决定 diff --git a/maa_mcp/core.py b/maa_mcp/core.py index 718feba..7a27580 100644 --- a/maa_mcp/core.py +++ b/maa_mcp/core.py @@ -97,6 +97,12 @@ class ControllerInfo: - 使用 connect_adb_device(device_name) 或 connect_window(window_name) 建立连接 - 可连接多个设备/窗口,每个连接返回独立的控制器 ID + 坐标约定:连接默认 target_short_side=720,可指定其他正整数或 None(原尺寸)。 + OCR、动作和 Pipeline 都使用控制器完整截图坐标,不一定等于设备物理坐标。 + screencap 默认不额外缩放;裁图或显式缩放后定位,请设 include_metadata=True, + 按 image_to_controller 的 scale 和 offset 换算后再操作。 + 非 720 连接模式需要对应尺度的 Pipeline 模板和 ROI。 + 2. 串行自动化执行循环(流程 1 之后选择此流程进入串行模式) ⭐ 标准工作循环:截图(screencap) → OCR识别(ocr) → 分析内容 → 执行操作(click/swipe等) → 重复直到完成 - 调用 ocr(controller_id) 对指定设备进行屏幕截图和 OCR 识别 diff --git a/maa_mcp/vision.py b/maa_mcp/vision.py index 989b384..cea85c0 100644 --- a/maa_mcp/vision.py +++ b/maa_mcp/vision.py @@ -15,16 +15,24 @@ from maa_mcp.paths import get_screenshots_dir -def _crop_region(image, region: Optional[Tuple[int, int, int, int]]): - """按 (x, y, w, h) 裁剪 cv2 图像,region 为 None 时返回原图。自动 clamp 到图像边界。""" +def _crop_bounds(image_shape, region): + """返回实际使用的整数裁剪范围,图像与坐标变换共用同一边界。""" + H, W = image_shape[:2] if region is None: - return image + return (0, 0, W, H) x, y, w, h = region - H, W = image.shape[:2] x = max(0, min(int(x), W - 1)) y = max(0, min(int(y), H - 1)) w = max(1, min(int(w), W - x)) h = max(1, min(int(h), H - y)) + return (x, y, w, h) + + +def _crop_region(image, region: Optional[Tuple[int, int, int, int]]): + """按 (x, y, w, h) 裁剪 cv2 图像,region 为 None 时返回原图。自动 clamp 到图像边界。""" + if region is None: + return image + x, y, w, h = _crop_bounds(image.shape, region) return image[y : y + h, x : x + w] @@ -93,19 +101,19 @@ def _scale_region_to_image( return (x * sx, y * sy, w * sx, h * sy) -def _apply_screencap_pipeline( +def _prepare_screencap( raw, region: Optional[Tuple[int, int, int, int]], resolution: Optional[int], ): - """screencap 图像处理流水线(纯函数,可独立单测)。 + """处理截图,并返回落盘图坐标到控制器坐标的变换。 流程: 1. 若 resolution 非 None:按短边归一化 2. 若 region 非 None 且做了归一化:按比例缩放 region(从 raw 坐标系 → new 坐标系) 3. 按 region 裁剪(无 region 则返回全图) - region 语义:坐标空间永远是 raw 设备原始分辨率。函数负责缩放。 + region 语义:坐标空间是控制器完整截图,不一定是设备物理分辨率。 """ raw_h, raw_w = raw.shape[:2] @@ -120,20 +128,33 @@ def _apply_screencap_pipeline( region, raw_shape=(raw_h, raw_w), new_shape=(new_h, new_w) ) - return _crop_region(image, region) + # 使用舍入后的真实尺寸和 clamp 后的原点,避免非整数比例下的坐标漂移。 + new_h, new_w = image.shape[:2] + x, y, w, h = _crop_bounds(image.shape, region) + sx, sy = raw_w / new_w, raw_h / new_h + transform = {"scale": (sx, sy), "offset": (x * sx, y * sy)} + cropped = image if region is None else image[y : y + h, x : x + w] + return cropped, transform + + +def _apply_screencap_pipeline(raw, region, resolution): + """仅返回处理后的图像。""" + image, _ = _prepare_screencap(raw, region, resolution) + return image def _screencap( controller_id: str, region: Optional[Tuple[int, int, int, int]] = None, - resolution: Optional[int] = 720, -) -> Optional[str]: + resolution: Optional[int] = None, + include_metadata: bool = False, +) -> Optional[Union[str, dict]]: """截图核心实现:拉 controller 截图 + 应用图像处理流水线 + 落盘。 region 语义(重要): - region 的 (x, y, w, h) **永远在设备原始分辨率坐标系**下,不在落盘图 - 坐标系下。函数会按归一化比例自动缩放。AI 无需关心输出图实际是 - 720p 还是其他尺寸。 + region 的 (x, y, w, h) 位于控制器完整截图坐标系,与 OCR、click 和 + Pipeline 相同。默认不额外缩放;显式指定 resolution 后,落盘图坐标 + 需要换算回控制器坐标。裁图坐标还需加回裁剪原点。 """ controller: Controller | None = object_registry.get(controller_id) if not controller: @@ -142,7 +163,7 @@ def _screencap( if raw is None: return None - image = _apply_screencap_pipeline(raw, region, resolution) + image, transform = _prepare_screencap(raw, region, resolution) # 落盘 screenshots_dir = get_screenshots_dir() @@ -154,7 +175,17 @@ def _screencap( return None # 记录当前会话保存的截图文件路径,用于退出时清理 _saved_screenshots.append(filepath) - return str(filepath.absolute()) + path = str(filepath.absolute()) + if not include_metadata: + return path + return { + "path": path, + "controller_id": controller_id, + "coordinate_system": "controller", + "coordinate_size": (raw.shape[1], raw.shape[0]), + "image_size": (image.shape[1], image.shape[0]), + "image_to_controller": transform, + } def _ocr_impl( @@ -165,10 +196,9 @@ def _ocr_impl( 参数: - controller_id: 控制器 ID - - region: 可选 (x, y, w, h),用 maafw JOCR 的 roi+roi_offset 内置机制做 - 区域 OCR 并自动把返回 box 坐标补偿到原窗口坐标系。 - roi_offset = roi,所以返回坐标等价于"在未裁剪原图上的位置", - 可以直接拿去 click()。 + - region: 可选 (x, y, w, h),位于控制器截图坐标系。 + MaaFramework 会自动把区域识别结果还原到完整截图坐标系, + 返回的 box 可以直接用于 click()。 返回值: - 成功:返回识别结果列表 @@ -188,11 +218,9 @@ def _ocr_impl( if image is None: return None - # 用 maafw 内置的 roi + roi_offset 做区域 OCR + 坐标补偿 - # roi_offset 与 roi 取相同值,返回的 box 坐标就是原窗口坐标系 if region is not None: x, y, w, h = int(region[0]), int(region[1]), int(region[2]), int(region[3]) - ocr_param = JOCR(roi=(x, y, w, h), roi_offset=(x, y, w, h)) + ocr_param = JOCR(roi=(x, y, w, h)) else: ocr_param = JOCR() @@ -213,7 +241,7 @@ def _ocr_impl( - controller_id: 控制器 ID,由 connect_adb_device() 或 connect_window() 返回 - region: 可选 (x, y, w, h) 整型元组,指定屏幕上的一个矩形区域,只对该区域做 OCR。 适用于"我只想看搜框 / 侧边栏 / 某个对话框"等局部场景。 - 返回结果里的 box 坐标已自动加回 region 偏移,仍是原屏幕坐标系,直接拿去 click 即可。 + region 和返回的 box 均位于控制器完整截图坐标系,可直接用于 click。 不传则对整屏 OCR(默认行为,较慢)。 返回值: @@ -247,24 +275,34 @@ def ocr( 参数: - controller_id: 控制器 ID,由 connect_adb_device() 或 connect_window() 返回 - region: 可选 (x, y, w, h) 整型元组,指定屏幕上的一个矩形区域,只截并保存该区域。 - ⚠️ region 坐标空间 = **设备原始分辨率**(不是落盘图分辨率)。 - 若设备是 1080p (1920×1080),region 的 x/y/w/h 都按 1080p 坐标想。 - 函数会按归一化比例自动缩放 region,无需 AI 关心输出图实际尺寸。 + region 使用控制器完整截图坐标,与 OCR、click 和 Pipeline 相同, + 不一定等于设备物理分辨率。默认控制器短边为 720。 适用于"我只想看搜框附近 / 某个按钮周围"的场景,省传输与读图时间。 不传则截全屏(默认行为)。 - - resolution: 可选整数,短边归一化目标(像素),默认 720。 + - resolution: 可选整数,短边归一化目标(像素),默认 None,不额外缩放。 720p 不锁死 16:9:按短边等比缩放,原图长宽比保留。 例如:1920×1080 → 1280×720;1080×1920 → 720×1280; 1280×800 (16:10) → 1152×720。 - 传 None 跳过归一化,落盘图为原始设备分辨率(region 也在原始空间)。 + 显式缩放仅影响保存的图像,不改变 OCR、click 或 Pipeline 坐标系。 + 裁图中的坐标需要加回裁剪原点;缩放后的坐标还需换算比例。 + - include_metadata: 默认 False,保持返回路径字符串。裁剪或显式缩放后需要 + 定位操作时设为 True,返回路径、图像尺寸、坐标基准及变换信息。 返回值: - - 成功:返回截图文件的绝对路径,可通过 read_file 工具读取图片内容 + - 成功且 include_metadata=False:返回截图文件的绝对路径 + - 成功且 include_metadata=True:返回对象: + path: 截图文件绝对路径,可用于读图和 save_captured_image + controller_id: 控制器 ID;coordinate_system: "controller" + coordinate_size: 控制器完整截图 [宽, 高],也是 OCR、动作及 Pipeline 的坐标基准 + image_size: 保存图像的 [宽, 高] + image_to_controller: {scale: [sx, sy], offset: [ox, oy]} + 图中点 (u, v) 对应控制器点 (u*sx+ox, v*sy+oy),点击前取整。 + 变换包含实际裁剪原点和边界修正,只对应本次截图的尺寸和画面。 - 失败:返回 None 多模态裁图工作流(你 M3 可用): 1. screencap(cid) → Read 源图 → 多模态识别目标元素(如按钮、图标、文字块) - 2. 推断目标元素 region (x, y, w, h)——按设备原始分辨率想 + 2. 推断目标元素 region (x, y, w, h),使用控制器完整截图坐标 3. screencap(cid, region=...) → 一步裁出 4. Read 裁剪结果 → 视觉验证是否为目标元素 5. 不满意就调 region 重试(UI 稳定时可多次迭代) @@ -277,9 +315,10 @@ def ocr( def screencap( controller_id: str, region: Optional[Tuple[int, int, int, int]] = None, - resolution: Optional[int] = 720, -) -> Optional[str]: - return _screencap(controller_id, region, resolution) + resolution: Optional[int] = None, + include_metadata: bool = False, +) -> Optional[Union[str, dict]]: + return _screencap(controller_id, region, resolution, include_metadata) # --------------------------------------------------------------------------- diff --git a/maa_mcp/win32.py b/maa_mcp/win32.py index 2f29667..3da2768 100644 --- a/maa_mcp/win32.py +++ b/maa_mcp/win32.py @@ -64,6 +64,9 @@ def find_window_list() -> list[str]: - screencap_method: 截图方式,默认 "FramePool"(一般无需修改) - mouse_method: 鼠标输入方式,默认 "PostMessage"(一般无需修改) - keyboard_method: 键盘输入方式,默认 "PostMessage"(一般无需修改) + - target_short_side: 控制器截图短边,默认 720;可设为 1080 等正整数。 + 传 None 使用原始尺寸。OCR、动作和 Pipeline 均使用该控制器的截图坐标, + 非 720 模式需要匹配的模板及 ROI;screencap 的 resolution 不会改变此基准。 返回值: - 成功:返回窗口控制器 ID(字符串),用于后续所有窗口操作 @@ -107,7 +110,12 @@ def connect_window( screencap_method: str = "FramePool", mouse_method: str = "PostMessage", keyboard_method: str = "PostMessage", + target_short_side: Optional[int] = 720, ) -> Optional[str]: + if target_short_side is not None and ( + type(target_short_side) is not int or target_short_side <= 0 + ): + raise ValueError("target_short_side must be a positive integer or None") window: DesktopWindow | None = object_registry.get(window_name) if not window: return None @@ -128,9 +136,12 @@ def connect_window( mouse_method=mouse_enum, keyboard_method=keyboard_enum, ) - # 设置默认截图短边为 1080p - # 电脑屏幕通常较大,使用更高清的截图 - window_controller.set_screenshot_target_short_side(1080) + if target_short_side is None: + configured = window_controller.set_screenshot_use_raw_size(True) + else: + configured = window_controller.set_screenshot_target_short_side(target_short_side) + if not configured: + return None if not window_controller.post_connection().wait().succeeded: return None @@ -141,6 +152,7 @@ def connect_window( "screencap_method": screencap_method, "mouse_method": mouse_method, "keyboard_method": keyboard_method, + "target_short_side": target_short_side, } controller_info_registry[controller_id] = ControllerInfo( diff --git a/tests/test_coordinates.py b/tests/test_coordinates.py new file mode 100644 index 0000000..d684853 --- /dev/null +++ b/tests/test_coordinates.py @@ -0,0 +1,350 @@ +"""Coordinate contracts tested with native MaaFramework and synthetic frames.""" + +import asyncio +import json +from pathlib import Path +from types import SimpleNamespace + +import cv2 +import numpy as np +import pytest +from maa.controller import CustomController +from maa.pipeline import JColorMatch, JRecognitionType +from maa.resource import Resource +from maa.tasker import Tasker + +from maa_mcp import adb, control, vision, win32 +from maa_mcp.core import controller_info_registry, mcp, object_registry +from maa_mcp.paths import get_resource_dir + + +class ImageController(CustomController): + def __init__(self, image): + self.image = image + self.points = [] + super().__init__() + + def connect(self): + return True + + def request_uuid(self): + return "maamcp-coordinate-test" + + def screencap(self): + return self.image + + def touch_down(self, contact, x, y, pressure): + self.points.append((x, y)) + return True + + def touch_up(self, contact): + return True + + +@pytest.fixture +def image_controller(): + controller = ImageController(np.zeros((1440, 2560, 3), dtype=np.uint8)) + assert controller.post_connection().wait().succeeded + cid = object_registry.register(controller) + try: + yield cid, controller + finally: + object_registry.unregister(cid) + + +@pytest.fixture(params=["adb", "win32"]) +def connection_probe(request, monkeypatch, image_controller): + _, controller = image_controller + if request.param == "win32": + monkeypatch.setattr( + win32, "Win32Controller", lambda *args, **kwargs: controller + ) + source = SimpleNamespace(hwnd=123) + connect = win32.connect_window + else: + monkeypatch.setattr(adb, "AdbController", lambda *args, **kwargs: controller) + source = SimpleNamespace( + adb_path="unused", + address="unused", + screencap_methods=0, + input_methods=0, + config="{}", + ) + connect = adb.connect_adb_device + source_id = object_registry.register(source) + connections = [] + + def connect_probe(**options): + cid = getattr(connect, "fn", connect)(source_id, **options) + if cid: + connections.append(cid) + return cid + + try: + yield connect_probe, controller + finally: + object_registry.unregister(source_id) + for cid in connections: + object_registry.unregister(cid) + controller_info_registry.pop(cid, None) + + +@pytest.mark.integration +@pytest.mark.parametrize( + "options,shape", + [ + ({}, (720, 1280, 3)), + ({"target_short_side": 1080}, (1080, 1920, 3)), + ({"target_short_side": None}, (1440, 2560, 3)), + ], +) +def test_connection_screenshot_and_click_share_coordinates( + monkeypatch, tmp_path, connection_probe, options, shape +): + connect, controller = connection_probe + monkeypatch.setattr(vision, "get_screenshots_dir", lambda: tmp_path) + cid = connect(**options) + assert cid is not None + assert controller_info_registry[cid].connection_params[ + "target_short_side" + ] == options.get("target_short_side", 720) + capture = getattr(vision.screencap, "fn", vision.screencap) + path = capture(cid) + assert isinstance(path, str) + image = cv2.imread(path) + assert image.shape == shape + click = getattr(control.click, "fn", control.click) + assert click(cid, image.shape[1] // 2, image.shape[0] // 2, duration=0) + assert controller.points[-1] == (1280, 720) + + +@pytest.mark.parametrize("target", [0, -1, False, 1.5]) +def test_invalid_resolution_is_rejected(connection_probe, target): + connect, _ = connection_probe + with pytest.raises(ValueError, match="target_short_side"): + connect(target_short_side=target) + + +@pytest.mark.parametrize("target", [720, None]) +def test_failed_resolution_configuration_does_not_publish_controller( + connection_probe, monkeypatch, target +): + connect, controller = connection_probe + method = ( + "set_screenshot_use_raw_size" + if target is None + else "set_screenshot_target_short_side" + ) + monkeypatch.setattr(controller, method, lambda _: False) + monkeypatch.setattr( + controller, "post_connection", lambda: pytest.fail("Unexpected connection") + ) + previous_ids = set(object_registry.list()) + assert connect(target_short_side=target) is None + assert set(object_registry.list()) == previous_ids + + +@pytest.mark.integration +def test_scaled_clamped_crop_metadata_maps_back_to_click( + monkeypatch, tmp_path, image_controller +): + cid, controller = image_controller + assert controller.set_screenshot_target_short_side(1080) + monkeypatch.setattr(vision, "get_screenshots_dir", lambda: tmp_path) + capture = getattr(vision.screencap, "fn", vision.screencap) + info = capture( + cid, region=(1500, 900, 600, 400), resolution=720, include_metadata=True + ) + assert info["controller_id"] == cid + assert info["coordinate_system"] == "controller" + assert info["coordinate_size"] == (1920, 1080) + assert info["image_size"] == (280, 120) + assert cv2.imread(info["path"]).shape == (120, 280, 3) + assert info["image_to_controller"] == {"scale": (1.5, 1.5), "offset": (1500, 900)} + sx, sy = info["image_to_controller"]["scale"] + ox, oy = info["image_to_controller"]["offset"] + x, y = round(140 * sx + ox), round(60 * sy + oy) + click = getattr(control.click, "fn", control.click) + assert click(cid, x, y, duration=0) + assert controller.points[-1] == (2280, 1320) + + +@pytest.mark.integration +def test_portrait_metadata_accounts_for_rounded_dimensions( + monkeypatch, tmp_path, image_controller +): + cid, controller = image_controller + controller.image = np.zeros((1537, 901, 3), dtype=np.uint8) + assert controller.set_screenshot_use_raw_size(True) + monkeypatch.setattr(vision, "get_screenshots_dir", lambda: tmp_path) + info = vision._screencap(cid, resolution=720, include_metadata=True) + width, height = info["image_size"] + sx, sy = info["image_to_controller"]["scale"] + assert width == 720 + assert width * sx == pytest.approx(901) + assert height * sy == pytest.approx(1537) + assert sx != sy + assert info["image_to_controller"]["offset"] == (0, 0) + + +@pytest.mark.integration +@pytest.mark.parametrize("raw_mode", [False, True]) +def test_pipeline_template_requires_matching_controller_scale( + image_controller, raw_mode +): + _, controller = image_controller + template = np.random.default_rng(7).integers( + 0, 256, size=(40, 60, 3), dtype=np.uint8 + ) + canonical = np.full((720, 1280, 3), 128, dtype=np.uint8) + canonical[200:240, 400:460] = template + controller.image = cv2.resize( + canonical, (2560, 1440), interpolation=cv2.INTER_NEAREST + ) + assert controller.set_screenshot_use_raw_size(raw_mode) + resource = Resource() + assert ( + resource.post_bundle(Path(__file__).parent / "fixtures" / "bundle_minimal") + .wait() + .succeeded + ) + assert resource.override_image("coordinate-test.png", template) + tasker = Tasker() + tasker.bind(resource, controller) + pipeline = { + "Entry": { + "recognition": "DirectHit", + "next": ["Match"], + "timeout": 100, + "rate_limit": 10, + "pre_delay": 0, + "post_delay": 0, + }, + "Match": { + "recognition": "TemplateMatch", + "template": "coordinate-test.png", + "threshold": 0.99, + "pre_delay": 0, + "post_delay": 0, + }, + } + try: + detail = tasker.post_task("Entry", pipeline).wait().get() + matches = [ + n + for n in detail.nodes + if n.name == "Match" and n.recognition and n.recognition.hit + ] + assert bool(matches) == (not raw_mode) + finally: + tasker.post_stop().wait() + + +@pytest.mark.integration +def test_screencap_metadata_through_mcp(monkeypatch, tmp_path, image_controller): + from fastmcp import Client + + cid, _ = image_controller + monkeypatch.setattr(vision, "get_screenshots_dir", lambda: tmp_path) + + async def call_tool(): + async with Client(mcp) as client: + tools = {tool.name: tool for tool in await client.list_tools()} + schemas = { + name: (getattr(tool, "input_schema", None) or tool.inputSchema)[ + "properties" + ] + for name, tool in tools.items() + } + params = schemas["screencap"] + assert params["resolution"]["default"] is None + assert params["include_metadata"]["default"] is False + for name in ("connect_window", "connect_adb_device"): + assert schemas[name]["target_short_side"]["default"] == 720 + result = await client.call_tool( + "screencap", {"controller_id": cid, "include_metadata": True} + ) + info = json.loads(result.content[0].text) + assert info["coordinate_size"] == [1280, 720] + assert info["image_size"] == [1280, 720] + assert info["image_to_controller"] == { + "scale": [1.0, 1.0], + "offset": [0.0, 0.0], + } + assert Path(info["path"]).is_file() + + asyncio.run(call_tool()) + + +@pytest.mark.integration +def test_ocr_region_contract_without_model(monkeypatch, image_controller): + cid, controller = image_controller + controller.image = np.zeros((720, 1280, 3), dtype=np.uint8) + controller.image[130:170, 120:210] = (0, 255, 0) + controller.image[250:290, 240:340] = (0, 255, 0) + resource = Resource() + assert ( + resource.post_bundle(Path(__file__).parent / "fixtures" / "bundle_minimal") + .wait() + .succeeded + ) + tasker = Tasker() + tasker.bind(resource, controller) + + def recognize_region(reco_type, param, image): + assert reco_type == JRecognitionType.OCR + # OCR and ColorMatch share native ROI handling; avoid model weights in CI. + return tasker.post_recognition( + JRecognitionType.ColorMatch, + JColorMatch( + lower=[[0, 255, 0]], + upper=[[0, 255, 0]], + connected=True, + roi=param.roi, + roi_offset=param.roi_offset, + ), + image, + ) + + adapter = SimpleNamespace(post_recognition=recognize_region) + monkeypatch.setattr(vision, "get_or_create_tasker", lambda _: adapter) + monkeypatch.setattr(vision, "check_ocr_files_exist", lambda: True) + try: + results = vision._ocr_impl(cid, region=(100, 100, 250, 100)) + assert isinstance(results, list) + assert [tuple(result.box) for result in results] == [(120, 130, 90, 40)] + finally: + tasker.post_stop().wait() + + +@pytest.mark.integration +def test_region_ocr_excludes_neighbor_and_returns_global_boxes( + monkeypatch, image_controller +): + resource_dir = get_resource_dir() + model_dir = resource_dir / "model" / "ocr" + if not all( + (model_dir / name).is_file() for name in ("det.onnx", "rec.onnx", "keys.txt") + ): + pytest.skip("Local OCR model is not installed") + + cid, controller = image_controller + image = np.full((720, 1280, 3), 255, dtype=np.uint8) + cv2.putText(image, "TARGET", (120, 155), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2) + cv2.putText(image, "DECOY", (240, 260), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2) + controller.image = image + + resource = Resource() + assert resource.post_bundle(resource_dir).wait().succeeded + tasker = Tasker() + tasker.bind(resource, controller) + monkeypatch.setattr(vision, "get_or_create_tasker", lambda _: tasker) + try: + results = vision._ocr_impl(cid, region=(100, 100, 250, 100)) + assert isinstance(results, list) + assert [result.text for result in results] == ["TARGET"] + x, y, width, height = results[0].box + assert 100 <= x < x + width <= 350 + assert 100 <= y < y + height <= 200 + finally: + tasker.post_stop().wait() diff --git a/tests/test_vision.py b/tests/test_vision.py index fa45e1b..4d72ae9 100644 --- a/tests/test_vision.py +++ b/tests/test_vision.py @@ -170,23 +170,23 @@ class TestApplyScreencapPipeline: """用真实 numpy 数组测 screencap 的图像处理流水线。 真实场景:AI 拿到 screencap 截图后想做局部 OCR,需要传 region。 - region 坐标空间 = 设备原始分辨率;流水线负责缩放到输出图坐标系。 + region 位于控制器完整截图坐标系;显式缩放时流水线负责转换到输出图坐标系。 """ - def test_default_720p_no_region(self): - """raw 1920×1080 + 无 region + 默认 720:全图归一到 1280×720""" + def test_explicit_720p_no_region(self): + """raw 1920×1080 + 无 region + 显式 720:全图归一到 1280×720""" raw = np.zeros((1080, 1920, 3), dtype=np.uint8) out = _apply_screencap_pipeline(raw, region=None, resolution=720) assert out.shape == (720, 1280, 3) - def test_default_720p_portrait(self): - """raw 1080×1920 + 无 region + 默认 720:全图归一到 720×1280""" + def test_explicit_720p_portrait(self): + """raw 1080×1920 + 无 region + 显式 720:全图归一到 720×1280""" raw = np.zeros((1920, 1080, 3), dtype=np.uint8) out = _apply_screencap_pipeline(raw, region=None, resolution=720) assert out.shape == (1280, 720, 3) def test_region_in_raw_coords_1080p(self): - """raw 1920×1080 + region (in 1080p 空间) + 默认 720: + """raw 1920×1080 + region (in 1080p 空间) + 显式 720: region 按 2/3 缩放后裁到 1280×720 上 → 输出 (400, 533, 3) """ raw = np.zeros((1080, 1920, 3), dtype=np.uint8) @@ -198,7 +198,7 @@ def test_region_in_raw_coords_1080p(self): assert out.shape == (400, 533, 3) def test_region_in_raw_coords_portrait(self): - """raw 1080×1920 + region (in 竖屏 1080p 空间) + 默认 720: + """raw 1080×1920 + region (in 竖屏 1080p 空间) + 显式 720: region 按 2/3 缩放后裁到 720×1280 上 → 输出 (400, 533, 3) """ raw = np.zeros((1920, 1080, 3), dtype=np.uint8) @@ -208,7 +208,7 @@ def test_region_in_raw_coords_portrait(self): assert out.shape == (400, 533, 3) def test_region_no_scale_when_already_720p(self): - """raw 1280×720 + region + 默认 720:缩放=1,no-op""" + """raw 1280×720 + region + 显式 720:缩放=1,no-op""" raw = np.zeros((720, 1280, 3), dtype=np.uint8) out = _apply_screencap_pipeline( raw, region=(100, 100, 800, 600), resolution=720 @@ -267,9 +267,9 @@ class TestScreencapSaveRoundtrip: @pytest.mark.parametrize( "raw_shape,region,resolution,expected_shape", [ - # 默认 720p 全图 + # 显式 720p 全图 ((1080, 1920, 3), None, 720, (720, 1280, 3)), - # 默认 720p 竖屏 + # 显式 720p 竖屏 ((1920, 1080, 3), None, 720, (1280, 720, 3)), # region + 720p 横屏 ((1080, 1920, 3), (100, 100, 800, 600), 720, (400, 533, 3)), From 951f63779efa49cd717d92306fea2c9c4352d859 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=A5=E4=B8=80=E4=B8=80?= <1204244136@qq.com> Date: Sat, 19 Sep 2026 14:11:51 +0800 Subject: [PATCH 2/2] fix(vision): validate screenshot resolution before processing Reject non-integer, boolean, and non-positive resolutions with ValueError before controller access or OpenCV resizing. Cover invalid inputs and preserve the None passthrough mode. --- maa_mcp/vision.py | 9 ++++++--- tests/test_vision.py | 30 ++++++++++++++++++++++++------ 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/maa_mcp/vision.py b/maa_mcp/vision.py index cea85c0..2f8251b 100644 --- a/maa_mcp/vision.py +++ b/maa_mcp/vision.py @@ -51,14 +51,14 @@ def _resize_short_edge(image, target_short_edge: int): Args: image: cv2 图像 (numpy.ndarray)。 - target_short_edge: 目标短边像素数,必须 > 0。 + target_short_edge: 目标短边像素数,必须是 > 0 的 int(不接受 bool)。 Returns: 缩放后的图像;若短边已等于 target,则原图返回(no-op)。 """ - if target_short_edge <= 0: + if type(target_short_edge) is not int or target_short_edge <= 0: raise ValueError( - f"target_short_edge 必须 > 0,实际: {target_short_edge}" + f"target_short_edge 必须 > 0 且类型为 int,实际: {target_short_edge!r}" ) h, w = image.shape[:2] short = min(h, w) @@ -156,6 +156,8 @@ def _screencap( Pipeline 相同。默认不额外缩放;显式指定 resolution 后,落盘图坐标 需要换算回控制器坐标。裁图坐标还需加回裁剪原点。 """ + if resolution is not None and (type(resolution) is not int or resolution <= 0): + raise ValueError("resolution must be a positive integer or None") controller: Controller | None = object_registry.get(controller_id) if not controller: return None @@ -280,6 +282,7 @@ def ocr( 适用于"我只想看搜框附近 / 某个按钮周围"的场景,省传输与读图时间。 不传则截全屏(默认行为)。 - resolution: 可选整数,短边归一化目标(像素),默认 None,不额外缩放。 + 必须是正整数或 None;非法参数会抛出明确的参数错误。 720p 不锁死 16:9:按短边等比缩放,原图长宽比保留。 例如:1920×1080 → 1280×720;1080×1920 → 720×1280; 1280×800 (16:10) → 1152×720。 diff --git a/tests/test_vision.py b/tests/test_vision.py index 4d72ae9..61e4831 100644 --- a/tests/test_vision.py +++ b/tests/test_vision.py @@ -13,6 +13,7 @@ import pytest from pathlib import Path +from maa_mcp import vision from maa_mcp.vision import ( _apply_screencap_pipeline, _crop_region, @@ -78,13 +79,30 @@ def test_custom_resolution_1080p(self): out = _resize_short_edge(img, 1080) assert out is img - def test_invalid_resolution_raises(self): - """resolution <= 0 抛 ValueError""" + @pytest.mark.parametrize( + "resolution", + [0, -1, 1.5, 720.0, True, False, "720", None, float("nan"), float("inf")], + ) + def test_invalid_resolution_raises(self, resolution): + """非法尺寸必须在调用 OpenCV 前抛出明确的 ValueError。""" img = np.zeros((720, 1280, 3), dtype=np.uint8) - with pytest.raises(ValueError, match="必须 > 0"): - _resize_short_edge(img, 0) - with pytest.raises(ValueError, match="必须 > 0"): - _resize_short_edge(img, -1) + with pytest.raises(ValueError, match="target_short_edge.*int"): + _resize_short_edge(img, resolution) + + +@pytest.mark.parametrize( + "resolution", + [0, -1, 1.5, 720.0, True, False, "720", float("nan"), float("inf")], +) +def test_screencap_rejects_invalid_resolution_before_controller_access(monkeypatch, resolution): + monkeypatch.setattr( + vision.object_registry, + "get", + lambda _: pytest.fail("Invalid resolution must be rejected before controller access"), + ) + capture = getattr(vision.screencap, "fn", vision.screencap) + with pytest.raises(ValueError, match="resolution must be a positive integer or None"): + capture("unused", resolution=resolution) # ---------------------------------------------------------------------------