使用Python 3.6中的matplotlib.image打开一个.jpg图像。

12

我想在Python中使用matplotlib打开一张JPG图片。编辑器是'Spyder',Python3.6版本,操作系统是Windows 7。

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

# Read in the image and print some stats
image = mpimg.imread(r'C:\Users\xxx\Python Code\mountain.jpg')
print('This image is: ',type(image), 
     'with dimensions:', image.shape)

但是我遇到了以下错误......它说除了'.png'之外没有支持其他图像格式。

错误:-- image = mpimg.imread(r'C:\Users\xxx\Python Code\mountain.jpg')

  File "C:\temp\Continuum\anaconda3\lib\site-packages\matplotlib\image.py", 
line 1284, in imread
    'more images' % list(handlers))

ValueError: Only know how to handle extensions: ['png']; with Pillow 
installed matplotlib can handle more images.

我查看了各种文档,发现要打开 '.jpg' 图像,必须安装 'Pillow'。如果本机的 matplotlib 调用无法打开图像,则会自动回退到 'Pillow'。(如果我说错了,请纠正我)

所以我安装了 'Pillow',但仍然遇到错误。

你能告诉我我错过了什么吗?(奇怪的是这段代码在另一台计算机上运行正常,我无法验证该计算机上安装了哪个库)


5
如果未安装或找不到PIL或pillow,则会出现此错误。您可以通过自行导入“import PIL”来测试它。 - ImportanceOfBeingErnest
我已经在代码中添加了“import PIL”的语句。但仍然出现相同的错误。 “Import PIL”执行时没有任何错误。 - Tanay
2
这意味着Pillow的安装在某个时候出了问题。尝试卸载并重新安装。 - ImportanceOfBeingErnest
1
我也看到了下面的Github帖子,它与我遇到的问题非常相似。但是我仍然不知道如何解决它。https://github.com/python-pillow/Pillow/issues/2945 - Tanay
我必须使用Anaconda安装pillows,然后在Jupyter中使用以下代码:from PIL import Imageimg = Image.open("./apples.jpg") plt.imshow(img) - Golden Lion
显示剩余9条评论
2个回答

12

Matplotlib需要PIL(Python Imaging Library)才能处理.jpg格式。为了使用它,您需要安装Pillow(即PIL的分支)。

使用PIP进行安装

pip install pillow 
      or 
pip3 install pillow

使用Conda进行安装

conda install pillow

0

您需要安装PIL。请确保您正在使用Anaconda Python发行版。前往此链接或输入以下命令直接安装PIL

 conda install -c anaconda pillow 

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