首页 > 解决方案 > ImportError 与 keras.preprocessing

问题描述

我正在关注Tensorflow 的图像分类教程。在运行以下代码时 -

import PIL
import tensorflow as tf
from tensorflow import keras

sunflower_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/592px-Red_sunflower.jpg"
sunflower_path = tf.keras.utils.get_file('Red_sunflower', origin=sunflower_url)
img = keras.preprocessing.image.load_img(sunflower_path, target_size=(180, 180))

我在最后一行收到以下错误。

ImportError: Could not import PIL.Image. The use of `load_img` requires PIL.

如何解决上述问题?

请注意,我的 conda 工作环境(python=3.8,Tensorflow=2.3)上安装了枕头。

标签: pythontensorflowkeraspython-imaging-library

解决方案


该错误表明您尚未pillow在计算机上安装。如果您使用的是 conda,那么您必须这样做

conda install pillow

如果您不使用 conda,那么我会尝试

pip install pillow

编辑 1:如果您已经在 conda 环境中安装了 PIL,请尝试

conda uninstall PIL
conda install Pillow

编辑 2:如果您可能安装了旧版本的 Pillow,但无法与您的环境中安装的 TensorFlow/Keras 版本一起使用,重新安装 Pillow 可能会有所帮助。


推荐阅读