如何在OpenCV Python中检测全黑色图像?

Har*_*ari 8 python opencv python-2.7

我想在python中编写代码,以便在输入图像完全是黑色并且其中没有其他颜色时打印文本.哪些功能要使用?

ebe*_*tos 12

试试这个:

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

您基本上检查所有像素值是否为0(黑色).


Vin*_*nte 5

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

上面的代码片段由 @ebeneditos 提供,这是一个很好的想法,但在我的测试中,opencv 在捕获彩色图像时返回断言错误。

根据opencv社区countNonZero()只能处理单通道图像。因此,一种简单的解决方案是在计算像素之前将图像转换为灰度。这里是:

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