Python图像识别脚本异常:未找到图像时抛出ImageNotFoundException
问题解决:pyautogui图像识别异常处理与误判问题
问题根源
你写的代码里,pyautogui.locateOnScreen()在找不到匹配图像时,不会返回None,而是直接抛出ImageNotFoundException,程序会直接崩溃中断,根本走不到else分支——这就是你看到报错的核心原因。
而把confidence降到0.7后出现误判,是因为阈值太低,屏幕上一些像素相似的区域被错误识别成了目标图像。
解决方案1:用try-except捕获异常(最适合新手)
直接捕获函数抛出的异常,在异常块里处理“找不到图像”的逻辑,这是最直接适配原代码逻辑的修改方式:
from pyautogui import * import pyautogui import time import keyboard import random import win32api, win32con while True: try: # 尝试查找图像,找到则执行正常分支 pyautogui.locateOnScreen('orange shape.png', confidence=0.8) print("I can see it") time.sleep(0.5) except ImageNotFoundException: # 找不到图像时触发这个分支 print("I am unable to see it") time.sleep(0.5)
解决方案2:用locateAllOnScreen避免异常
locateAllOnScreen()找不到图像时会返回空迭代器,不会抛出异常,我们可以把它转成列表后判断是否为空:
from pyautogui import * import pyautogui import time import keyboard import random import win32api, win32con while True: # 转成列表,找到图像则列表有内容,找不到则为空列表 matches = list(pyautogui.locateAllOnScreen('orange shape.png', confidence=0.8)) if matches: print("I can see it") time.sleep(0.5) else: print("I am unable to see it") time.sleep(0.5)
额外优化建议(解决误判问题)
- 加上
grayscale=True参数,将图像转为灰度模式识别,减少颜色干扰,提升匹配准确性:pyautogui.locateOnScreen('orange shape.png', confidence=0.8, grayscale=True) - 用
region参数缩小识别区域(参数格式为(左边界, 上边界, 宽度, 高度)),比如只识别屏幕的某个固定区域,既缩短识别时间,也降低误判概率:# 示例:仅识别屏幕左上角800x600的区域 pyautogui.locateOnScreen('orange shape.png', confidence=0.8, region=(0,0,800,600))
内容的提问来源于stack exchange,提问作者icegalaxy1223
相关产品推荐
相关产品推荐

