quantumbutterfly
quantumbutterfly

Reputation: 1953

Opencv python - check if particular pixel value in image

Lets say I have an image in opencv. E.g.

img = cv2.imread(file_path)

Lets also say I have a pixel value. E.g.

pixel = np.array([200,200,200])

I want to know if there is any pixel in img with the value of pixel.

What is the best way to do this?

I tried img.any(pixel) but that doesn't work. I know you can probably manually check using loops, but I'm sure a more elegant way must exist.

I just need a boolean yes or no response.

Upvotes: 2

Views: 2568

Answers (2)

Saurav Panda
Saurav Panda

Reputation: 566

I dont know how you actually need to find, but in case you need to see if any pixel in image has value of 200 just do this:

print((a==200).any())

you will get true if pixel with value 200 exists in the array, else you will get false. Hope this solves your query.

Upvotes: 0

timgeb
timgeb

Reputation: 78790

My first idea is to reshape the array and then do the in check after converting the shaped array to a list.

Demo:

>>> a = np.array([[[1, 2, 3], [4,5,6]], [[7,8,9], [10,11,12]]])
>>> a
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])
>>> shaped = a.reshape(a.size/3, 3)
>>> shaped
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
>>> [4, 5, 6] in shaped.tolist()
True
>>> [6, 5, 4] in shaped.tolist()
False

(More efficient solutions might exist.)

Upvotes: 1

Related Questions