JustDante
JustDante

Reputation: 31

How to check if a numpy array holds a specific rgb value?

import numpy as np
import cv2 

img = cv2.imread('screens/bigMessages.png')
# print(img)
img_array = np.array(img)
c = (255, 95 , 173)
points = np.where(np.all(img == c, axis=-1))
print(points)

I am trying to find out if this array has this (255, 95 , 173) RGB value. and I know the image I am loading does. I found out with a photoshop color picker from that same image.

Now this code returns: (array([], dtype=int64), array([], dtype=int64))

I do not understand and I do not know enough numpy, I just need it for this one thing, please help.

Upvotes: 1

Views: 2093

Answers (1)

paime
paime

Reputation: 3552

I think you got it right, if the target pixel is in your array it should be ok, see:

import numpy as np

H, W, C = 32, 32, 3
img = np.random.randint(low=0, high=255, size=(H, W, C))
target = (255, 95, 173)
img[14, 26] = target

print(f"{                (img == target         ).shape = }")
print(f"{          np.all(img == target, axis=-1).shape = }")
print(f"{np.where( np.all(img == target, axis=-1)     ) = }")

which prints:

                (img == target         ).shape = (32, 32, 3)
          np.all(img == target, axis=-1).shape = (32, 32)
np.where( np.all(img == target, axis=-1)     ) = (array([14]), array([26]))

If nothing is returned, then the taget pixel is not here. It might be because RGB values are swapped, or many other things (data type, wrong value returned by photoshop etc.).

You better display your image in matplotlib and explore it from there. Here you can see that when moving the cursor on the right position (14, 26), then the RGB value corresponds:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.imshow(img)
plt.show()

pixel value

Upvotes: 3

Related Questions