Search code examples
pythonpython-3.xpyautoguipynput

How to click on the nth pixel of an image with python (NOT WHAT YOU THINK)


I have some code to determine the location of every black pixel on the screen:

last_pixel = 0

time.sleep(0.01)
ss = pyautogui.screenshot()
ss.save(r"Screenshots\ss.png")
image = Image.open(r"Screenshots\ss.png", "r")
pixels = list(image.getdata())
for n, pixel in enumerate(pixels):
    if pixel == (0, 0, 0):
        print(pixel, n)
        last_pixel = n

However, this returns, for example, "(0, 0, 0) 2048576", and to click on a specific point on the screen, at least with pynput/pyautogui, you need an x, y kind of thing, how can i possibly click on a pixel of an image (screenshot) with simply a number like: its the 2048576th pixel, click it.


Solution

  • If you know the size of your image (width x height), converting pixel number to [x, y] coordinates is a trivial math problem.

    img_width = 1920
    img_height = 1080
    
    pixel_number = 2000
    
    pixel_row, pixel_col = divmod(pixel_number, img_width)
    

    I'm not sure whether the pixels are stored in row-major or column-major order. If they're stored in column-major order, all you need to do is:

    pixel_col, pixel_row = divmod(pixel_number, img_height)