📜  使用Python - OpenCV 检查图像是否为空

📅  最后修改于: 2022-05-13 01:54:44.615000             🧑  作者: Mango

使用Python - OpenCV 检查图像是否为空

先决条件: OpenCV基础

OpenCV(开源计算机视觉)是一个计算机视觉库,包含对图片或视频进行操作的各种功能。它最初由 Intel 开发,但后来由 Willow Garage 维护,现在由 Itseez 维护。这个库是跨平台的,它支持多种编程语言,如Python、C++ 等。在本文中,我们将尝试使用 OpenCV (开源计算机视觉)检查打开的图像是否为空。

为此,需要安装 OpenCV 库:

pip install opencv-python

为了实现这一目标,我们将使用 cv2.imread() 方法,如果该方法读取图像,则返回图像坐标矩阵,否则返回 None。

输入图像:

文件.png

例子:

在这个例子中,我们将读取图像并检查是否找到。

Python3
# Importing OpenCV library
import cv2
 
# user define function
# that return None or
def check_empty_img(img):
    # Reading Image
    # You can give path to the
    # image as first argument
    image = cv2.imread(img)
 
    # Checking if the image is empty or not
    if image is None:
        result = "Image is empty!!"
    else:
        result = "Image is not empty!!"
 
    return result
     
# driver node
img = "Gfg.png"
 
# Calling and printing
# the function
print(check_empty_img(img))


Python3
# Importing OpenCV library
import cv2
 
# user define function
# that return None or
def check_empty_img(url):
    # Reading Image
    # You can give path to the
    # image as first argument
    image = cv2.imread(url)
 
    # Checking if the image is empty or not
    if image is None:
        result = "Image is empty!!"
    else:
        result = "Image is not empty!!"
 
    return result
     
# driver node
img = "geek.png"
 
# Calling and printing
# the function
print(check_empty_img(img))


输出:

Image is not empty!!

示例 2:

在这个例子中,这里没有找到图像。

蟒蛇3

# Importing OpenCV library
import cv2
 
# user define function
# that return None or
def check_empty_img(url):
    # Reading Image
    # You can give path to the
    # image as first argument
    image = cv2.imread(url)
 
    # Checking if the image is empty or not
    if image is None:
        result = "Image is empty!!"
    else:
        result = "Image is not empty!!"
 
    return result
     
# driver node
img = "geek.png"
 
# Calling and printing
# the function
print(check_empty_img(img))

输出:

Image is empty!!