pyautogui中getPixel()无法返回坐标,脚本运行异常求助
问题分析与解决办法
问题原因
- 像素格式不匹配:
pyautogui.screenshot()返回的图像默认是RGBA模式,每个像素是包含4个值的元组(R, G, B, A),而你定义的color是3个值的RGB元组,导致getpixel的结果永远无法匹配,嵌套循环会一直执行,不断打印"searching...",看起来像脚本停止。 - break作用范围有限:内层的
break只能跳出y的循环,即使找到目标颜色,x的循环仍会继续执行下一个横坐标的搜索。 - 无循环终止条件:外层的
while True是死循环,即使找到坐标也不会停止运行。 - 初始
location可能为空:如果第一次locateOnScreen(image)没找到图片,location为None,后续使用region=location会引发错误。
解决方法
1. 统一像素格式
将颜色改为RGBA格式(不透明场景下透明度值用255),或者将截图转换为RGB模式:
# 方法1:修改color为RGBA格式 color = (54, 175, 49, 255) # 方法2:将截图转为RGB模式 s = pyautogui.screenshot(region=location).convert('RGB')
2. 找到颜色后终止所有循环
通过标记位跳出多层循环,同时将截图内的相对坐标转换为屏幕绝对坐标:
color = (54, 175, 49) image = 'green.png' location = pyautogui.locateOnScreen(image) # 先判断初始图片是否找到 if not location: print("初始未找到目标图片") exit() while True: current_loc = pyautogui.locateOnScreen(image, region=location) if current_loc: s = pyautogui.screenshot(region=current_loc).convert('RGB') found_flag = False for x in range(s.width): for y in range(s.height): print("searching...") if s.getpixel((x, y)) == color: print("found") # 转换为屏幕绝对坐标 screen_x = current_loc.left + x screen_y = current_loc.top + y print(f"目标坐标:({screen_x}, {screen_y})") found_flag = True break if found_flag: break # 跳出x轴循环 if found_flag: break # 跳出while死循环 else: print("未找到目标图片") break
3. 优化搜索效率
嵌套逐像素搜索效率极低,改用numpy批量处理可大幅提升速度:
import numpy as np import pyautogui color = (54, 175, 49) image = 'green.png' location = pyautogui.locateOnScreen(image) if not location: print("初始未找到目标图片") exit() while True: current_loc = pyautogui.locateOnScreen(image, region=location) if current_loc: s = pyautogui.screenshot(region=current_loc).convert('RGB') img_array = np.array(s) # 批量匹配颜色,获取所有符合条件的坐标 match_positions = np.where((img_array == color).all(axis=2)) if len(match_positions[0]) > 0: # 取第一个匹配的坐标 y, x = match_positions[0][0], match_positions[1][0] screen_x = current_loc.left + x screen_y = current_loc.top + y print(f"found,目标坐标:({screen_x}, {screen_y})") break else: print("区域内未找到目标颜色") else: print("未找到目标图片") break
内容的提问来源于stack exchange,提问作者masterJohnson
相关产品推荐
相关产品推荐

