是否在屏幕上定位颜色位置



我想用pyautogui点击屏幕上的特定颜色,但为此我需要它的位置,我找不到任何关于该主题的有用信息。我正在尝试制作一个钢琴瓷砖自动舔舐器,为此我考虑识别瓷砖的颜色并点击它。

您可以使用pyautogui:找到颜色位置

import pyautogui
color = (255, 255, 255)
s = pyautogui.screenshot()
for x in range(s.width):
for y in range(s.height):
if s.getpixel((x, y)) == color:
pyautogui.click(x, y)  # do something here

考虑制作较小区域的屏幕截图,以更快地识别像素。

pyautogui.screenshot(region=(0,0, 300, 400))

参数是要捕获的区域的左、顶、宽和高的四个整数元组。您甚至可以只抓取每个磁贴的一个像素,使其更好地工作。我不认为制作整个屏幕的屏幕截图是个好主意,尤其是当平铺速度很快的时候。

我会怎么做:

  1. 使用pyautogui.position()获取瓦片出现的每个区域的一个像素的坐标(假设瓦片的颜色是实心的,并且在游戏过程中没有变化(
  2. 使用getpixel()获取瓦片像素的RGB值
  3. 在循环中检查步骤1中坐标的像素是否与步骤2中获得的RGB值相同
  4. 如果是,请致电pyautogui.click()

这里是另一个统计区域中像素数量的版本:

import pyautogui
def checkForRGBValues(start=(0,0), end=(50,50), R=255, G=255, B=255): #start/end/r/g/b value, I put some standard values for testing
x = int(end[0]-start[0] + 1) #calculates x value between start and end
y = int(end[1]-start[1] + 1)  #calculates y value between start and end
how_many_pixels_found = 0 #nothing found yet 
for x in range(start[0], end[0] + 1, 1): #loops through x value
for y in range(start[1], end[1] + 1, 1): #loops through y value
if pyautogui.pixel(x, y)[0] == R and pyautogui.pixel(x, y)[1] == G and pyautogui.pixel(x, y)[2] == B: #checks if the wanted RGB value is in the region
how_many_pixels_found = how_many_pixels_found + 1 #adds one to the result
y = y + 1
x = x + 1
return how_many_pixels_found #returns the total value of pixels with the wanted color in the region.
x = checkForRGBValues((150,200), (200,250), R=60, G=63, B=65)
print(x)

这是我的第一篇文章!:(我也遇到了同样的问题,但我找到了解决办法。我的代码可能没有遵循任何编程标准,但它正在工作哈哈哈!我两个月前开始用Python编程(20年前有一些经验(QBasic/C/Java(,但从来没有专业知识(。请告诉我是否为你工作,是否有什么可以改进的地方。我希望我能用这个帖子来帮助别人,因为这个网站在过去的两个月里一直在帮助我!

def checkForRGBValues(start=(0,0), end=(50,50), R=255, G=255, B=255):
x = int(end[0]-start[0] + 1)
y = int(end[1]-start[1] + 1)
# print(x)
# print(y)
for x in range(start[0], end[0] + 1, 1):
for y in range(start[1], end[1] + 1, 1):
print(str(x) + "/" + str(y))
if pyautogui.pixel(x, y)[0] == R and pyautogui.pixel(x, y)[1] == G and pyautogui.pixel(x, y)[2] == B:
print("Color found")
with open("color_found.txt", "a") as file_found:
file_found.write(str(x) + "/" + str(y))
file_found.write("n")
else:
with open("color_not_found.txt", "a") as file:
file.write(str(x) + "/" + str(y))
file.write("n")
y = y + 1
x = x + 1

checkForRGBValues((150,200), (200,250), R=255, G=0, B=0) #if nothing (0,0), (50,50)

最新更新