[英]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.我想在 python 中编写代码以在输入图像完全黑色并且其中不存在其他颜色时打印文本。 Which are the functions to be used?
要使用哪些功能?
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).您基本上检查所有像素值是否为 0(黑色)。
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.上面由@ebeneditos 提供的代码片段是一个很好的想法,但在我的测试中,opencv 在捕获彩色图像时返回断言错误。
According opencv community , countNonZero() can handle only single channel images .根据opencv 社区, countNonZero()只能处理单通道图像。 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.