Python 从ImageGrab定位黑色像素的位置

Python 从ImageGrab定位黑色像素的位置,python,python-3.x,python-imaging-library,imagegrab,Python,Python 3.x,Python Imaging Library,Imagegrab,我目前正在创建一个PianoTiles AI,它必须从ImageGrab中定位所有黑色像素。我已经得到了图像抓取的所有位置,但是我需要找出那里是否有黑色像素,如果有,它们在哪里,这样我的AI就可以点击它们。贝娄,我已经把我的密码剪断了 我已经在网上浏览过了,但什么也找不到。我认为代码是这样的 from PIL import ImageGrab, ImageOps class Coordinates: lines = [ (520, 300, 525, 7

我目前正在创建一个PianoTiles AI,它必须从ImageGrab中定位所有黑色像素。我已经得到了图像抓取的所有位置,但是我需要找出那里是否有黑色像素,如果有,它们在哪里,这样我的AI就可以点击它们。贝娄,我已经把我的密码剪断了

我已经在网上浏览过了,但什么也找不到。我认为代码是这样的

from PIL import ImageGrab, ImageOps    

class Coordinates:    
    lines = [    
    (520, 300, 525, 760),    
    (630, 300, 635, 760),    
    (740, 300, 745, 760),    
    (850, 300, 855, 760)]    
    restartcheck = (660, 590, 725, 645)    
    restartbtn = (695, 615)    


blackpixelpositions = []    

def findtiles():    
    for line in Coordinates.lines:  
        i = ImageGrab.grab(line)  
        for pixel in i.getdata():  
            #if pixel is black  
            # x, y = pixel position  
             blackpixelpositions.append((x,y))  

我所需要的只是上面的代码,然后给我黑色像素的位置。

I.getdata()有一个问题,就是它会使数据变平,也就是说,你会丢失像素坐标(除非你手动跟踪)。 所以你只知道存在一个黑色像素,但不知道在哪里。 您可以改用getpixel:

def get_black_pixels(image):
    found = []
    width, height = image.size
    for y in range(height):
        for x in range(width):
            if all(map(lambda x: x < 20, image.getpixel((x,y)))):
                found.append((x,y))
    return found
def get_black_像素(图像):
找到=[]
宽度,高度=image.size
对于范围内的y(高度):
对于范围内的x(宽度):
如果全部(映射(λx:x<20,image.getpixel((x,y))):
找到。追加((x,y))
返回发现
该行:

all(map(lambda x: x < 20, image.getpixel((x,y))))
all(map(lambda x:x<20,image.getpixel((x,y)))

只需检查所有值(r、g、b)是否低于20,您可以将其更改为其他阈值。

您应该尝试避免在图像上循环,并使用
getpixel()
等函数访问每个像素,因为它非常慢——特别是对于大型图像,如果您使用的是现代4-5k屏幕

通常最好将PIL图像转换为Numpy数组,然后使用矢量化Numpy例程来处理图像。因此,具体来说,假设您通过抓屏或打开文件获得PIL图像:

im = Image.open('someFile.png')
然后,您可以从图像中创建一个Numpy数组,如下所示:

n = np.array(im)
blacks = np.where((n[:, :, 0:3] == [0,0,0]).all(2)))
并搜索如下所示的黑色像素:

n = np.array(im)
blacks = np.where((n[:, :, 0:3] == [0,0,0]).all(2)))
这将为您提供黑色像素的
x
坐标数组和
y
坐标数组,例如,您可以执行以下操作:

xcoords, ycoords = np.where((n[:, :, 0:3] == [0,0,0]).all(2))