Search code examples
pythonimageperformancepixel

Compare pixels as fast as possible


I am trying to find exact RGB on my screen with python and compare them as fast as possible. The code uses PIL ImageGrab to get the pixels on the screen. Is it possible to make it faster?

from PIL import Image, ImageGrab
px = ImageGrab.grab().load()

for y in range(pointY, rangeY, 1):
    for x in range(pointX, rangeX, 1):
        color = px[x, y] # Screen pixel
        img = pix[0,0] # First pixel of my image

        if img[0] != color[0] or img[1] != color[1] or img[2] != color[2]:
            continue
        else:
            # Compare the whole image

Solution

  • You can use numpy to compare the colors.

    This will return a 2D array the size of the screen, where every occurrence of your color is marked with True.

    import numpy as np
    from PIL import Image, ImageGrab
    screen_grab = np.asarray(ImageGrab.grab())
    my_color = np.asarray(pix[0,0])
    
    # returns 2D array of comparisons
    result = np.all(screen_grab==my_color, axis=-1)
    

    If you just want to check if it contains the color then do

    # returns true if the screen contains your color anywhere
    result_any = np.any(result)
    

    If you want to get the coordinates of the matching pixels you can do

    # returns coordinates of the pixels that match
    result_idx = np.argwhere(result)