PyAutoGUI实时图像定位卡顿求助:优化鼠标定位效率
解决PyAutoGUI重复加载图片导致定位延迟的问题
你用预加载图片提升速度的思路是对的,但选错了工具——IPython的Image类是用来在交互式环境里显示图片的,并非PyAutoGUI需要的图像数据对象。PyAutoGUI的locateOnScreen方法只认PIL(Pillow)库的Image对象,所以会抛出image don't have attribute named mode的错误。
正确的预加载实现代码
import pyautogui as a from PIL import Image import time # 预加载目标图片为PIL Image对象,仅执行一次 target_img = Image.open("example.png") while True: # 直接使用预加载的对象,无需重复读取本地文件 pixel = a.locateOnScreen(target_img) if pixel is None: time.sleep(0.05) # 加小延迟降低CPU占用 continue # 获取图片中心并移动鼠标 center_x, center_y = a.center(pixel) a.moveTo(center_x, center_y)
额外优化建议
- 加入
time.sleep(0.05)可以避免程序持续占用满CPU资源,同时不影响实时性 - 若需要提升图像匹配的容错率,可安装
opencv-python后,在locateOnScreen中添加confidence参数,示例:a.locateOnScreen(target_img, confidence=0.8)
内容的提问来源于stack exchange,提问作者maxmatch
相关产品推荐
相关产品推荐

