如何从图像文件> numpy数组>单一RGB颜色的x / y坐标列表转换

时间:2019-04-11 18:56:37

标签: python arrays numpy

enter image description here

从上方的2x2像素图像中创建一个numpy数组(为清楚起见,将其放大):

import numpy as np
from PIL import Image

img = Image.open('2x2.png')
pixels = np.array(img)

数组看起来像这样,每个像素都由其各自的[R,G,B]值表示:

>>> pixels
array([[[255,   0,   0],
        [  0, 255,   0]],

       [[  0,   0, 255],
        [255,   0,   0]]], dtype=uint8)

现在,我需要生成“所有红色像素”的x / y坐标数组,因此所有值均为[255, 0, 0]的数组元素。所需的结果坐标数组如下所示:

array([[ 0,  0],
       [ 1,  1 ]])

实现此目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以尝试:

temp = (pixels == [255,0,0]).all(axis=-1)
# [[ True False]
#  [False  True]]
result = np.asarray(np.where(temp)).T
print(result)

# print
# [[0 0]
#  [1 1]]

答案 1 :(得分:0)

我发现这可行:

np.argwhere((pixels==[255,0,0]).all(axis=2))
array([[0, 0],
       [1, 1]]