简体   繁体   中英

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):

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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