属性错误:'str'对象没有属性'shape' - 使用 scikit-image 调整图像大小时



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

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

最新更新