AttributeError: 'str' object has no attribute 'shape' - when resizing image using scikit-image

AttributeError: 'str' object has no attribute 'shape' - when resizing image using scikit-image

我正在尝试遍历目录并使用 scikit-image 调整每个图像的大小,但我不断收到以下错误:

b'scene01601.png'
Traceback (most recent call last):
  File "preprocessingdatacopy.py", line 16, in <module>
    image_resized = resize(filename, (128, 128))
  File "/home/briannagopaul/PycharmProjects/DogoAutoencoder/venv/lib/python3.6/site-packages/skimage/transform/_warps.py", line 104, in resize
    input_shape = image.shape
AttributeError: 'str' object has no attribute 'shape'

我的代码:

import skimage
from sklearn import preprocessing
from skimage import data, color
import os
from skimage.transform import resize, rescale
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
directory_in_str = "/home/briannagopaul/imagemickey/"
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
    print(file)
    filename = os.fsdecode(file)
    if filename.endswith(".png"):
        image_resized = resize(filename, (128, 128))
        img = mpimg.imread(file)
        imgplot = plt.imshow(img)
        plt.show()
        filename.shape()

首先,除非代码 运行 与图像位于同一目录中,否则您需要在文件名中指定目录:

for file in os.listdir(directory):
    print(file)
    filename = directory_in_str + os.fsdecode(file)

但是为了解决您的问题,您已经通过 mpimg.imread 行读取图像并将该图像存储为名为 img 的 numpy 数组。使用那个 img 变量,您可以 运行 它通过其余的行:

    if filename.endswith(".png"):
        img = mpimg.imread(filename)
        image_resized = resize(img, (128, 128))
        imgplot = plt.imshow(img)
        plt.show()
        print(img.shape)

请注意,我将对 filename 的两个单独调用更改为 img。那是因为 filename 只是文件的名称而不是实际文件,在您的情况下称为 img.