Python没有读取文件夹的图片



我正在尝试循环读取文件夹的图片,并将其添加到我的模型中。一些图像重新出现在两个文件夹中,但由于某些原因,无法从文件路径中读取。

from pathlib import Path
import numpy as np
import joblib
from keras.preprocessing import image
from keras.applications import vgg16
# Path to folders with training data
dog_path = Path("training_data") / "dogs"
not_dog_path = Path("training_data") / "not_dogs"
images = []
labels = []
# Load all the not-dog images
for img in not_dog_path.glob("*.png"):
# Load the image from disk
img = image.load_img(img)
# Convert the image to a numpy array
image_array = image.img_to_array(img)
# Add the image to the list of images
images.append(image_array)
# For each 'not dog' image, the expected value should be 0
labels.append(0)

但我得到了以下错误:

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-11-0338d9d50366> in <module>
15 for img in not_dog_path.glob("*.png"):
16     # Load the image from disk
---> 17     img = image.load_img(img)
18 
19     # Convert the image to a numpy array
~Anaconda3libsite-packageskeras_preprocessingimageutils.py in load_img(path, grayscale, color_mode, target_size, interpolation)
108         raise ImportError('Could not import PIL.Image. '
109                           'The use of `load_img` requires PIL.')
--> 110     img = pil_image.open(path)
111     if color_mode == 'grayscale':
112         if img.mode != 'L':
~Anaconda3libsite-packagesPILImage.py in open(fp, mode)
2816     for message in accept_warnings:
2817         warnings.warn(message)
-> 2818     raise IOError("cannot identify image file %r" % (filename if filename else fp))
2819 
2820 
OSError: cannot identify image file 'C:\Users\Yeshan\Desktop\Ex_Files_Deep_Learning_Image_Recog_Upd\Exercise Files\Ch05\training_data\not_dogs\._00381.png'

尝试使用:

from PIL import Image
# ....
image = Image.open(img)  # don't use same variable names

代替:

from keras.preprocessing import image
# ...
img = image.load_img(img)
# Convert the image to a numpy array
image_array = image.img_to_array(img)
# ...

此外,PIL默认支持numpy ndarray!

最新更新