You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python的pyautogui库从两张图片中匹配任意一张?

使用PyAutoGUI实现图片匹配的 fallback 逻辑

要实现「找不到第一张图时再匹配第二张」的逻辑,核心是利用PyAutoGUI的匹配返回结果或异常处理做分支判断,具体实现方式如下:

方法一:通过返回值判断(更简洁)

直接检查第一张图的匹配结果,若为None则尝试匹配第二张:

import pyautogui

# 定义两张目标图片路径
img1 = "button_first.png"
img2 = "button_second.png"

# 先尝试匹配第一张图,confidence参数需配合opencv-python使用
first_pos = pyautogui.locateOnScreen(img1, confidence=0.8, grayscale=True)
if first_pos:
    pyautogui.click(first_pos)
else:
    # 第一张找不到时匹配第二张
    second_pos = pyautogui.locateOnScreen(img2, confidence=0.8, grayscale=True)
    if second_pos:
        pyautogui.click(second_pos)
    else:
        print("两张目标图片都未找到")

方法二:捕获异常处理(更严谨)

利用PyAutoGUI匹配失败时抛出的ImageNotFoundException,通过try-except块处理分支:

import pyautogui

img1 = "button_first.png"
img2 = "button_second.png"

try:
    pos = pyautogui.locateOnScreen(img1, confidence=0.8)
    pyautogui.click(pos)
except pyautogui.ImageNotFoundException:
    try:
        pos = pyautogui.locateOnScreen(img2, confidence=0.8)
        pyautogui.click(pos)
    except pyautogui.ImageNotFoundException:
        print("两张图都未匹配到")

实用细节提示

  • 若要启用confidence参数提高匹配精度,需先安装opencv-python:pip install opencv-python
  • 添加grayscale=True可将屏幕转为灰度图匹配,提升速度和兼容性
  • 用region=(x, y, width, height)参数缩小搜索范围,能大幅减少匹配耗时

内容的提问来源于stack exchange,提问作者Gogland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 13:42:04