从路径列表中读取文件

Read files from a list of paths

我已经为一个深度学习项目下载了一个数据集,其中包含图像 (.png) 和每个图像的相应标签 (.txt)。我在列表 x 中有所有图像的路径。我想遍历这些路径,使用 cv2 预处理图像,并将新图像附加到新列表 images_data。但是,每次我尝试遍历它时,我都会收到同样的错误:cv2.error: OpenCV(4.1.1) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

即使我注释掉引发错误的那行代码,我在尝试调整图像大小时仍会遇到另一个错误。

这是我用来遍历列表的 for 循环:

images_data = []
    for file in x:
        img = cv2.imread(file)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img = cv2.resize(img, (80, 80))
        images_data.append(img)

我的 x 列表看起来很像这样: x = [car1.png, car2.png, car3.png, car4.png, car5.png]

如何解决这个错误?

该错误表明您的 img 变量为空,因此 cv2.imread(file) 未读取图像。您可以在阅读图像之后、转换颜色或调整大小之前检查这一点,使用简单的 if 情况:

if img is None: 
    print('Error reading image')
else:
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

或者使用os模块检查文件是否存在:

img = cv2.imread(file)
if os.path.isfile(file): 
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

os.path.isfile(file) 将 return True 如果文件存在。

我假设您的文件 car1.png, car2.png 等位于不同的文件夹中,并且与此脚本不在同一路径中,在这种情况下,您需要在执行之前将图像目录附加到文件名中可以阅读它。因此,例如,如果您的图像位于 '/home/Deep_Learning/Car_Images/' 中,那么在读取图像时,变量 file 必须包含字符串:/home/Deep_Learning/Car_Images/car1.png,对于第一张图像,而不仅仅是 car1.png。您可以像这样使用 python 的 os 模块来执行此操作:

import cv2
import os

# Directory of the images. Change it according your path
data_dir = '/home/Deep_Learning/Car_Images/' 

images_data = []
for file in x:
    file_name = os.path.join(data_dir, file) # Append the image folder with the image name

    if os.path.isfile(file_name) is False: #Check if image file exists
        print("Image file ", file_name, "does not exist")
    else:
        img = cv2.imread(file_name)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img = cv2.resize(img, (80, 80))
        images_data.append(img)