导入错误:找不到PIL模块。

360

我在 shell 中使用这个命令来安装 PIL:

easy_install PIL

我运行python并输入以下命令:import PIL。但是我遇到了下面的错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
ImportError: No module named PIL

我从未遇到过这样的问题,你认为是什么原因?


16
这篇文档页面实际上建议使用from PIL import Image,但这种方法不起作用。 - Janne Karila
2
@Janne 只需使用Import Image,PIL就可以开始工作了。 - Asma Gheisari
2
此时我建议使用easy_install Pillow。Pillow是PIL的一个分支,具有更好的打包和支持Python 3的功能。 - Lennart Regebro
1
你能否将被接受的答案更改为推荐Pillow的答案?正如@LennartRegebro所说,这个包在长期内更好。 - Josiah Yoder
2
请使用 pip install Pillow 命令进行安装。然后您就可以使用 import PIL.Image 进行导入。 - Tiago Martins Peres
31个回答

9
在Windows操作系统上,尝试检查PIL库存储的位置路径。在我的系统中,我发现该路径为:
\Python26\Lib\site-packages\pil instead of \Python26\Lib\site-packages\PIL  

pil文件夹重命名为PIL后,我能够加载PIL模块。


我也遇到了同样的导入错误。我使用easy_install安装了PIL。在site-packages中,它被安装在名为“PIL-1.1.7-py2.7-win32.egg”的目录中。根据您的建议,我将目录名称更改为PIL,然后它就可以工作了。感谢@Komla的帮助。 - shashaDenovo

8

解决这个问题最干净的方法是按照以下步骤进行。

步骤1:卸载PIL包。

pip uninstall PIL
步骤2:在Windows操作系统上使用以下pip命令安装Pillow。对于其他环境,请查看文章No module named PIL

在Windows上:

python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow

步骤 3:Python Imaging Library 中最重要的类是 Image 类,您可以按如下所示导入该类。

from PIL import Image
im = Image.open("myimage.jpg")

如果成功,此函数将返回一个 Image 对象。您现在可以使用实例属性来检查文件内容:
print(im.format, im.size, im.mode)

#Output: PPM (512, 512) RGB

这在我的 Windows 11 上运行良好。 - Devendra Singh
在其他 face_recognition/dlib 安装 python 修复方法都失败后,这个方法在我使用 macOS Monterey 上成功了。不过我需要将 Python 版本从 3.11 降级到 3.9。 - volvox

8

如果您使用Anaconda:

conda install pillow

1
我尝试了这个,但仍然无法导入PIL。 - john k
@johnktejik 你使用的是哪个Python和Anaconda的版本? - conor

7

我在Windows 10上遇到了同样的问题,这个方法对我有效:

pip install Pillow


6

您需要安装Image和pillow,这是与Python相关的技术。放心,命令行会为您处理一切。

输入以下命令:

python -m pip install image


6

使用Pillow替代PIL,它可以正常工作。

easy_install Pillow

或者

pip install Pillow

5
pip(3) uninstall Pillow
pip(3) uninstall PIL
pip(3) install Pillow

5
这对我在Ubuntu 20.04上的工作有效:
pip install image

在脚本中:

import image

2

请使用pil代替PIL

from pil import Image

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接