简体   繁体   English

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

[英]how to convert from image file > numpy array > list of x/y coords of a single RGB color

在此处输入图片说明

Create a numpy array from a 2x2 pixel image above (zoomed in for clarity): 从上面的2x2像素图像创建一个numpy数组(为清晰起见,将其放大):

import numpy as np
from PIL import Image

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

Array looks like this, with each pixel represented by its respective [R, G, B] values: 数组看起来像这样,每个像素都由其各自的[R,G,B]值表示:

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

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

Now I need to produce an array of x/y coordinates of 'all the red pixels', so all array elements with value [255, 0, 0] . 现在,我需要生成“所有红色像素”的x / y坐标数组,因此所有数组元素的值都为[255, 0, 0] The resulting array of coordinates needed looks like this: 所需的结果坐标数组如下所示:

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

What's the best way to achieve this? 实现此目标的最佳方法是什么?

You can try: 你可以试试:

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]]

I found that this works: 我发现这可行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM