导入错误:无法导入 PIL.图像.使用“array_to_img”需要 PIL



这非常棘手。我几乎已经尝试了互联网上的所有解决方案,但仍然无法解决这个问题。

如果我只是输入

from PIL import ImageFile
print(Image.__file__)

一切似乎都很好,系统将打印

C:UsersBenWangAnaconda3envstensorflowlibsite-packagesPILImage.py

喜欢这个

但是在我的编码中,如果我使用以下代码:

import sys
from PIL import Image
ImageFile.LOAD_TRUNCATED_IMAGES = True                 
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255

错误将如下所示:

ImportError                               Traceback (most recent call last)
<ipython-input-166-10a043c54408> in <module>()
      4 
      5 
----> 6 train_tensors = paths_to_tensor(train_files).astype('float32')/255
      7 valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
      8 test_tensors = paths_to_tensor(test_files).astype('float32')/255
<ipython-input-149-36af157e68bd> in paths_to_tensor(img_paths)
     11 
     12 def paths_to_tensor(img_paths):
---> 13     list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
     14     return np.vstack(list_of_tensors)
<ipython-input-149-36af157e68bd> in <listcomp>(.0)
     11 
     12 def paths_to_tensor(img_paths):
---> 13     list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
     14     return np.vstack(list_of_tensors)
<ipython-input-149-36af157e68bd> in path_to_tensor(img_path)
      4 def path_to_tensor(img_path):
      5     
----> 6     img = image.load_img(img_path, target_size=(224, 224))
      7     
      8     x = image.img_to_array(img)
~Anaconda3envstensorflowlibsite-packageskeras_preprocessingimageutils.py in load_img(path, grayscale, color_mode, target_size, interpolation)
    100         color_mode = 'grayscale'
    101     if pil_image is None:
--> 102         raise ImportError('Could not import PIL.Image. '
    103                           'The use of `array_to_img` requires PIL.')
    104     img = pil_image.open(path)
ImportError: Could not import PIL.Image. The use of `array_to_img` requires PIL.

我只是遇到了这样的问题。然后我安装枕头并重新启动内核(Spyder)来解决它。

最新更新