繁体   English   中英

从 ImageGrab 定位黑色像素的位置

[英]Locating Position of Black Pixels from ImageGrab

我目前正在创建一个 PianoTiles AI,它必须从 ImageGrab 中定位所有黑色像素。 我已经获得了 Image Grab 的所有位置,但是我需要找出那里是否有黑色像素,如果有,它们在哪里,以便我的 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))  

我所需要的只是上面的代码工作并给我黑色像素位置。

您应该尝试避免循环图像并使用诸如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)))

这将为您提供一个x坐标数组和一个黑色像素的y坐标数组,例如,您可以执行以下操作:

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

您对 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

线路:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM