首页 > 解决方案 > 为什么 CV2 不读取图像?

问题描述

我有一个训练图像和测试图像的数据集。我想要做的是输入训练图像并将它们调整为 150x150 大小。然后,根据图像文件的类名,将标签附加到数组“y”,这是我的标签数组。

但是,我收到此错误消息:

OpenCV(4.2.0) /io/opencv/modules/imgproc/src/resize.cpp:4045: error: (-215:Assertion failed) !ssize.empty() in function 'resize'

我的代码的相关部分如下:

nrows = 150
ncolumns = 150
channels = 3

def read(imgarray):
    x = []
    y = []

    for image in imgarray:
        try:
            x.append(cv2.resize(cv2.imread(image, cv2.IMREAD_COLOR), (nrows,ncolumns), interpolation=cv2.INTER_CUBIC))
        except Exception as e:
            print(str(e))
        if 'chicken' in image:
            y.append(0)
        elif 'cat' in image:
            y.append(1)
        elif 'scoop' in image:
            y.append(2)

    return x,y
x,y = read(train_images) #train_images is composed of ~5400 images, of mixed sizes and image formats

请有人告诉我为什么 CV2 没有“看到”图像以及如何调整图像大小?

编辑:示例图像名称为“../input/train/train/chicken (1438).jpg”,图像形状为 (340,594, 3)

我正在使用 Kaggle 内核,我的训练图像和测试图像存储在一个名为“输入”的目录中。训练图像在 input/train/train/img.jpg 中,测试图像在 input/test/img2.jpg 中。

更新:当我尝试在 train_images 中显示图像时:

for image in imgarray:
        #print(image)
        image = mpimg.imread(image)
        showplot = plt.imshow(image)

我收到了这个错误:

<built-in function imread> returned NULL without setting an error

这很奇怪,因为前面的代码工作得非常好,显示图像:

import matplotlib.image as mpimg
for i in train_images[0:3]:
    img=mpimg.imread(i)
    imgplot = plt.imshow(img)
    plt.show()

更新:当我输出导致错误的图像时,我得到这个:

Please check this image, has some issues ../input/train/train/scoop (1360).jpg
OpenCV(4.2.0) /io/opencv/modules/imgproc/src/resize.cpp:4045: error: (-215:Assertion failed) !ssize.empty() in function 'resize'

所以似乎应该工作的图像由于某种原因不起作用 在此处输入图像描述

这是引发错误的图像之一: 在此处输入图像描述

标签: pythonimageopencv

解决方案


简单地说,忽略有问题的图像。

添加标签的方式,即使丢失了一些图像,标签也会添加到数组中。

nrows = 150
ncolumns = 150
channels = 3

def read(imgarray):
    x = []
    y = []

    for image in imgarray:
        try:
            im = cv2.resize(cv2.imread(image), (nrows,ncolumns)
            x.append(im)
            print(type(im))
            print(im.shape)
            if 'chicken' in image:
                y.append(0)
            elif 'cat' in image:
                y.append(1)
            elif 'scoop' in image:
                y.append(2)
        except Exception as e:
            print(str(e))
            print(f'Please check this image, has some issues {image}')


    return x,y

x,y = read(train_images) #train_images is composed of ~5400 images, of mixed sizes and ima

推荐阅读