Hari
Hari

Reputation: 387

How to detect a full black color image in OpenCV Python?

I want to write code in python to print a text when the input image is perfectly black and no other colors are present in it. Which are the functions to be used?

Upvotes: 14

Views: 21393

Answers (2)

Vinícius Valente
Vinícius Valente

Reputation: 125

image = cv2.imread("image.jpg", 0)
if cv2.countNonZero(image) == 0:
    print "Image is black"
else:
    print "Colored image"

The snippet above provided by @ebeneditos it's a good ideia but in my tests opencv returns an assertion error when capturing a colored image.

According opencv community, countNonZero() can handle only single channel images. Thus, one simple solution would be to convert the image to grayscale before counting the pixels. Here it is:

gray_version = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
if cv2.countNonZero(gray_version) == 0:
    print("Error")
else:
    print("Image is fine")

Upvotes: 6

ebeneditos
ebeneditos

Reputation: 2612

Try this:

# open the file with opencv
image = cv2.imread("image.jpg", 0)
if cv2.countNonZero(image) == 0:
    print "Image is black"
else:
    print "Colored image"

You basically check if all pixel values are 0 (black).

Upvotes: 18

Related Questions