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

Pyautogui多图像检测异常:仅首个if语句触发

问题分析与解决方案

问题根源

你遇到的核心问题是elif的执行逻辑:只有当前面所有条件都不成立时,才会执行下一个elif分支。如果第一个if的条件始终为真(哪怕是误匹配),后面的elif永远不会触发。结合你的代码来看,还有两个潜在诱因:

  1. 第一个检测的confidence=0.6高于后两个的0.5,且检测区域与后两个重叠,容易出现误识别,导致第一个条件一直成立。
  2. 三个图像如果是互斥出现的,第一个检测的误判会直接阻断后续分支的执行。

解决方案

方案1:改用独立if语句(支持多图像同时触发)

如果需要多个图像同时存在时都执行对应操作,把所有elif改成独立的if,这样每个检测都会执行,不受前面条件的影响:

from pyautogui import *
import time
import keyboard
import random
import win32api, win32con

while 1:
    try:
        if locateOnScreen(r"C:\Users\Daniel Fernando\Desktop\Python\chromeDinosaur\assets\one.png", region=(755,325,120,120), grayscale = True, confidence=0.6) is not None:
            print("i see one")
            keyboard.send(" ")
            
        if locateOnScreen(r"C:\Users\Daniel Fernando\Desktop\Python\chromeDinosaur\assets\three.png", region=(740,325,120,120), grayscale = True, confidence=0.5) is not None:
            print("i see three")
            keyboard.send(" ")
              
        if locateOnScreen(r"C:\Users\Daniel Fernando\Desktop\Python\chromeDinosaur\assets\two.png", region=(740,325,120,120), grayscale = True, confidence=0.5) is not None:
            print("i see two")
            keyboard.send(" ")

    except ImageNotFoundException:
        print()

方案2:排查第一个检测的误匹配(适用于图像互斥场景)

如果三个图像同一时间只会出现一个,重点解决第一个检测的误判问题:

  1. 提高第一个检测的confidence值(比如调到0.8),减少误匹配概率
  2. 调整第一个检测的region,确保只覆盖one.png的专属区域,避免与其他图像区域重叠
  3. 先打印所有检测结果,直观排查误匹配情况:
from pyautogui import *
import time
import keyboard
import random
import win32api, win32con

while 1:
    try:
        # 先获取所有检测结果,便于排查
        one_result = locateOnScreen(r"C:\Users\Daniel Fernando\Desktop\Python\chromeDinosaur\assets\one.png", region=(755,325,120,120), grayscale = True, confidence=0.8)
        three_result = locateOnScreen(r"C:\Users\Daniel Fernando\Desktop\Python\chromeDinosaur\assets\three.png", region=(740,325,120,120), grayscale = True, confidence=0.5)
        two_result = locateOnScreen(r"C:\Users\Daniel Fernando\Desktop\Python\chromeDinosaur\assets\two.png", region=(740,325,120,120), grayscale = True, confidence=0.5)
        
        # 打印结果,确认是否存在误匹配
        print(f"one: {one_result}, three: {three_result}, two: {two_result}")
        
        if one_result is not None:
            print("i see one")
            keyboard.send(" ")
        elif three_result is not None:
            print("i see three")
            keyboard.send(" ")
        elif two_result is not None:
            print("i see two")
            keyboard.send(" ")

    except ImageNotFoundException:
        print()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:37:14