Pyautogui多图像检测异常:仅首个if语句触发
问题分析与解决方案
问题根源
你遇到的核心问题是elif的执行逻辑:只有当前面所有条件都不成立时,才会执行下一个elif分支。如果第一个if的条件始终为真(哪怕是误匹配),后面的elif永远不会触发。结合你的代码来看,还有两个潜在诱因:
- 第一个检测的
confidence=0.6高于后两个的0.5,且检测区域与后两个重叠,容易出现误识别,导致第一个条件一直成立。 - 三个图像如果是互斥出现的,第一个检测的误判会直接阻断后续分支的执行。
解决方案
方案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:排查第一个检测的误匹配(适用于图像互斥场景)
如果三个图像同一时间只会出现一个,重点解决第一个检测的误判问题:
- 提高第一个检测的
confidence值(比如调到0.8),减少误匹配概率 - 调整第一个检测的
region,确保只覆盖one.png的专属区域,避免与其他图像区域重叠 - 先打印所有检测结果,直观排查误匹配情况:
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
相关产品推荐
相关产品推荐

