从上方的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 ]])
实现此目标的最佳方法是什么?
答案 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]]