如何使用python单击图像的第n个像素不怎么想

问题描述

我有一些代码来确定屏幕上每个黑色像素的位置:

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):
        print(pixel,n)
        last_pixel = n

但是,这将返回例如“((0,0,0)2048576”),并且至少在使用pynput / pyautogui时,要单击屏幕上的特定点,您需要x,y之类的东西,我怎么可能只用一个数字单击图像的像素(屏幕截图),如:将其设为第2048576个像素,请单击它。

解决方法

将像素列表重塑为图像的尺寸,并获取该位置的像素索引。例如

import numpy as np

# 150 pixel long array
a = np.array(range(150))
# If your images was 15 pixels wide by 10 tall find the coordinates of pixel 108
np.where(a.reshape((10,15))==108)

输出

(array([7],dtype=int64),array([3],dtype=int64))
,

如果您知道图像的大小(宽x高),则将像素数转换为[x,y]坐标是一个简单的数学问题。

img_width = 1920
img_height = 1080

pixel_number = 2000

pixel_row,pixel_col = divmod(pixel_number,img_width)

我不确定像素是按行优先还是列主要顺序存储的。如果它们以列优先顺序存储,那么您要做的就是:

pixel_col,pixel_row = divmod(pixel_number,img_height)