为什么scipy.ndimage.io.imread返回PngImageFile,而不是值数组

2024-05-15 04:04:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两台不同的机器,安装了scipy 0.12和PIL。在一台计算机上,当我试图读取.png文件时,它返回一个整数数组,大小为(w x h x 3):

In[2]:  from scipy.ndimage.io import imread
In[3]:  out = imread(png_file)
In[4]:  out.shape
Out[4]: (750, 1000, 4)

在另一台计算机上,使用相同的图像文件,返回一个封装在数组中的PIL.PngImagePlugin.PngImageFile对象

In[2]: from scipy.ndimage.io import imread
In[3]: out = imread(png_file)
In[4]: out.shape
Out[4]: ()
In[5]:  out
Out[5]: array(<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x750 at 0x1D40050>, dtype=object)

我看不到任何方法来访问后一个对象的数据。

我有一种模糊的感觉,即PIL使用Png库读取图像的方式有问题,但是否有更具体的问题会导致这种行为?


Tags: infromioimportpilpng计算机scipy
1条回答
网友
1楼 · 发布于 2024-05-15 04:04:25

此错误(imread返回一个PIL.PngImagePlugin.PngImageFile类而不是数据数组)通常发生在安装了较旧版本的python映像库pillow或更糟的情况下。pillow是一个更新的PIL的“友好”分叉,绝对值得安装!

尝试更新这些包;(取决于您的python发行版)

# to uninstall PIL (if it's there, harmless if not)
$ pip uninstall PIL
# to install (or -U update) pillow
$ pip install -U pillow

然后尝试重新启动python shell并再次运行这些命令。

网友
2楼 · 发布于 2024-05-15 04:04:25

很可能您安装了一个不完整的Python映像库(PIL),SciPy依赖它来读取映像。PIL依赖于libjpeg包来加载JPEG图像,而zlib包来加载PNG图像,但是可以在没有这两者的情况下安装(在这种情况下,它无法加载库缺少的任何图像)。

我遇到的问题和上面描述的JPEG图像完全一样。不会引发错误消息,但是SciPy调用只返回一个包装的PIL对象,而不是将图像正确加载到数组中,这使得调试变得特别困难。然而,当我尝试直接使用PIL加载图像时,我得到:

> import Image
> im = Image.open('001988.jpg')
> im
   <JpegImagePlugin.JpegImageFile image mode=RGB size=333x500 at 0x20C8CB0>
> im.size
> (333, 500)
> pixels = im.load()
   IOError: decoder jpeg not available

所以我卸载了我的PIL副本,安装了丢失的libjpeg(在我的情况下,可能是zlib在您的情况下),重新安装了PIL来注册库的存在,现在使用SciPy加载图像工作得很好:

> from scipy import ndimage
> im = ndimage.imread('001988.jpg')
> im.shape
   (500, 333, 3)
> im
   array([[[112, 89, 48], ...
                     ..., dtype=uint8)
网友
3楼 · 发布于 2024-05-15 04:04:25

对于大多数用例,我相信libjpeglibz依赖关系是最可能的原因,正如Ken Chatfield的回答(接受的那个)中所提到的。

我还想提一下,如果有人在使用undertensorflow(特别是0.8.0)体验这种情况,我的意思是没有tensorflow,PIL确实起作用了,那么由于tensorflow的缺陷,可能会发生类似的情况。

github中报告的一些相关问题:

解决方法是在导入numpyscipyPIL之后移动import tensorflow as tf语句。具体处方见上述问题。

相关问题 更多 >

    热门问题