首页 > 解决方案 > 从屏幕截图中获取特定 RGB 值的 x,y 坐标列表

问题描述

我一直在尝试截取屏幕截图并找到特定颜色的每个 x,y 坐标。

from PIL import ImageGrab
import numpy as np

image = ImageGrab.grab()
indices = np.all(image == (209, 219, 221), axis=-1)
print(indices)
print(zip(indices[0], indices[1]))

当我运行我的代码时,我收到一个坐标,然后收到一条错误消息。

(1126, 555)
[1126, 555]
False

    print(zip(indices[0], indices[1]))
IndexError: invalid index to scalar variable.

它怎么不起作用?颜色在屏幕上。

标签: pythonimagenumpyimage-processingrgb

解决方案


我相信您在以下行中犯了错误:

indices = np.all(image == (209, 219, 221), axis=-1)

您可以直接遍历像素并获得您想要的结果:

from PIL import ImageGrab
import numpy as np

image = ImageGrab.grab()

color = (43, 43, 43)
indices = []

width, height = image.size

for x in range(width):
    for y in range(height):
        if image.getpixel((x, y)) == color:
            indices.append((x, y))

print(indices)

推荐阅读