使用 OpenCV Python 检查图像是否为空
OpenCV 是 Python 中的开源计算机视觉库。它是 Python 中的图像处理库之一,它使用 Python Numpy 库,因此所有图像数组都表示为 ndarray 类型。OpenCV-python 需要 numpy 库,我们需要确保 numpy 也安装在我们的 Python 解释器中。
在本文中,我们将看到使用 OpenCV Python 检查给定图像是否为空的不同方法。让我们观察输入输出场景,以了解如何使用 Python OpenCV 检查给定图像是否为空。
输入输出场景
假设我们有一个空白的输入图像,在输出中,我们将看到一个语句,说明给定图像是否为空。
输入图像
输出
图像为空
让我们讨论一下检查给定图像是否为空的不同方法。
具有唯一像素数
通常,空白/空图像在整个图像中具有更多唯一像素值。通过将唯一像素数与阈值进行比较,我们可以识别空图像。
示例
在此示例中,我们将使用 np.unique() 方法来获取唯一元素。
import numpy as np import cv2 def is_empty(img): # 读取图像 image = cv2.imread(img, 0) np.reshape(image, (-1,1)) u, count_unique = np.unique(image, return_counts =True) if count_unique.size< 10: return "Image is empty" else: return "Image is not empty" print(is_empty('whh.jpg'))
输入图像
输出
Image is empty
有标准差
空图像的标准差应接近于零。通常,空白/空图像可能在整个图像中具有更均匀的像素值。我们可以使用标准差来计算均匀度。如果该值低于某个阈值,那么我们可以说图像是空白的。
示例
让我们取一张"blank.png"图像并通过计算标准差来验证它。
import numpy as np import cv2 def is_empty(img): # 读取图像 image = cv2.imread(img, 0) np.reshape(image, (-1,1)) std_dev=np.std(image) if std_dev < 1: return "Image is empty" else: return "Image is not empty" print(is_empty('Blank.png'))
输出
Image is empty
我们使用 Numpy.std() 方法计算图像像素值的标准差。
对像素值求和
空/黑色图像的像素值为零。如果像素总和不等于零,那么我们可以说给定的图像不为空。如果总和等于零,则给定的图像为空。
示例
首先,我们将使用 numpy.zeros() 方法创建一个空白图像。然后验证给定的图像是否为空。
import numpy as np import cv2 blank_image2 = np.zeros((100,100,3), dtype=np.uint8) cv2.imwrite("result.jpg", blank_image2) def is_empty(img): # 读取图像 image = cv2.imread(img) # 检查图像是否为空 if np.sum(image) == 0: result = "Image is empty!" else: result = "Image is not empty!" return result print(is_empty('result.jpg'))
输出
Image is empty
结果图像的详细信息
结果图像由 numpy 数组数据的 cv2.imwrite() 方法创建。然后将 result.jpg 图像提供给定义的 is_empty() 函数,以检查给定的图像是否为空。