用scipy.ndimage.imread将图像文件加载到ndarray时出现错误

4

我正在尝试使用类似以下代码的方式将图像文件加载到ndarray中:

image_data = ndimage.imread(image_file).astype(float)

但是我遇到了这个错误:
/home/milos/anaconda3/envs/tensorflow/lib/python3.5/site-packages/scipy/ndimage/io.py in imread(fname, flatten, mode)
     23     if _have_pil:
     24         return _imread(fname, flatten, mode)
---> 25     raise ImportError("Could not import the Python Imaging Library (PIL)"
     26                       " required to load image files.  Please refer to"
     27                       " http://pypi.python.org/pypi/PIL/ for installation"

ImportError: Could not import the Python Imaging Library (PIL) required   to load image files.  Please refer to http://pypi.python.org/pypi/PIL/ for   installation instructions.

我已经在运行笔记本的环境中安装了Pillow,它也出现在pip freeze中。我还尝试从控制台运行它,但是出现了类似的错误。
有什么想法如何解决这个问题吗?或者有没有其他方法将图像加载到ndarray中?
2个回答

5
最终通过绕过scipy解决了问题:
from PIL import Image
img = Image.open(image_file)
image_data = np.array(img).astype(float)

我仍然想知道scipy的问题在哪里,如果你知道,请发布

编辑:

找到了更好的解决方案:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image_data = mpimg.imread(image_file)

这会创建一个numpy ndarray并将像素深度标准化为0-1,如果我想进行反向转换以检查其是否仍然良好,则此方法非常有效。
plt.imshow(image_data)

1
谢谢,我刚刚解决了Udacity深度学习课程的第一项任务,该任务依赖于scipy,并且在Python3上无法运行。我使用了您上面提供的解决方案直接替换它。 - Ben

0

我正在使用Python 2.7.x,并遇到了同样的问题。我也不确定在这种情况下scipy.ndimage.imread()发生了什么。卸载Pillow(PIL)并不能解决问题。所以,我做了和Milos提出的一样的事情,它起作用了:

import PIL
import numpy as np
image_file = './my_image.png'
image_data = np.array(PIL.Image.open(image_file)).astype(float)

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