3

I am currently working on a project with python and OpenCV. For one part of the project, I would like to check and see if one specific pixel (specifically the pixel with coordinate 100, 100) is not equal to the color black. My code is as follows.

import cv2

img = cv2.imread('/Documents/2016.jpg')

if img[100, 100] != [0, 0, 0]:
    print("the pixel is not black")

When I go and fun in the terminal I get this error.

File "/Documents/imCam.py", line 5, in <module>
if img[100, 100] != [0, 0, 0]:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

What am I doing wrong?

2 Answers 2

2

As it states, you're comparing lists with multiply entries, which is too unprecise.

You'll have to use numpy.any like

import cv2
import numpy as np

img = cv2.imread('/Documents/2016.jpg')

if np.any(img[100, 100] != 0):
    print("the pixel is not black")
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't this solution only work for colors that have the same value for all of B, G, and R? How could you compare to a different color? Like if img[100, 100] != [222, 12, 127]:
img[100, 100] != [222, 12, 127] returns a list of booleans, np.all() returns True iff each element of a given list is True. So np.all(img[100, 100] == [222, 12, 127]) will check if both colors match.
0
import cv2

image = cv2.imread('abc.jpg')

if image[50, 50, 0] != 0:
    print("the pixel is not black")

Try this :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.