python-opencv检测到图像是完全白色的



如何检测图像是否为白色。这意味着图像只有白色背景。这是黑色背景。示例代码:

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

您可以对输入图像执行bitwise_not操作,并应用相同的逻辑(这只是一个破解(:

image = cv2.imread("image.jpg", 0)
image = cv2.bitwise_not(image)
if cv2.countNonZero(image) == 0:
print "Image is white"
return True
else:
print "Black region is there"
return False

您可以使用numpy.all:

全白图像:

img_white = np.ones([10, 10, 3], np.uint8) * 255
res1 = np.all([img_white == 255])
print(res1) #=> True

非全白图像:

img_non_white = img_white.copy()
img_non_white[1, 1] = (100, 255, 255)
res2 = np.all([img_non_white == 255])
print(res2) #=> False

如果您使用OpenCV读取图像,那么它是一个numpy数组。所以你需要做的是检查里面有多少白点。

import cv2
import numpy as np
img = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE)
n._white_pix = np.sum(img == 255)

最新更新