scipy.misc 图像函数(e.x imread、imresize、imsave、imshow 等)上的 AttributeError、ImportError

AttributeError, ImportError on scipy.misc image functions (e.x imread, imresize, imsave, imshow etc.)

我在尝试导入或直接使用 scipy.misc 模块中包含的任何图像函数时遇到了两种错误。以下是 imread() 函数的两个错误示例:

>>> from scipy.misc import imread

ImportError: cannot import name 'imread' from 'scipy.misc'

>>> import scipy.misc                                                                                                                                                                
>>> scipy.misc.imread

AttributeError: module 'scipy.misc' has no attribute 'imread'

我做错了什么?

你没有做错任何事。这是由于 removal of the image functions from the scipy.misc module 自 SciPy 版本 1.2.0。我不知道他们为什么认为这些功能已弃用并删除了它们,但如果你想使用它们,你可以通过卸载当前版本并安装以前的版本来回滚到以前的 SciPy 版本:

pip uninstall scipy
pip install scipy==1.1.0

确保您也安装了 Pillow

pip install Pillow

如果您不想使用旧版本的 SciPy,则需要更改您的代码。根据每个弃用函数的官方文档,SciPy 建议如下:

  • fromimage(im) -> np.asarray(im)
  • imfilter() -> 直接使用 Pillow 过滤功能。
  • imread() -> imageio.imread()
  • imsave() -> imageio.imwrite()
  • imresize() -> numpy.array(Image.fromarray(arr).resize())
  • imrotate -> skimage.transform.rotate()
  • imshow() -> matplotlib.pyplot.imshow()
  • toimage() -> Image.fromarray()

假定安装以下库:

pip install numpy Pillow scikit-image imageio matplotlib

并导入它们:

import numpy as np, Pillow, skimage, imageio, matplotlib

此外,我引用了我发现的两个来源,提到了 scipy.misc 图片 I/O 功能的弃用:

来自 scipy.github.io:

The following functions in scipy.misc are deprecated: bytescale, fromimage, imfilter, imread, imresize, imrotate, imsave, imshow and toimage. Most of those functions have unexpected behavior (like rescaling and type casting image data without the user asking for that). Other functions simply have better alternatives.

来自imageio.readthedocs.io(特别是imread):

Transitioning from Scipy’s imread

Scipy is deprecating their image I/O functionality.

This document is intended to help people coming from Scipy to adapt to Imageio’s imread function. We recommend reading the user api and checkout some examples to get a feel of imageio.

Imageio makes use of variety of plugins to support reading images (and volumes/movies) from many different formats. Fortunately, Pillow is the main plugin for common images, which is the same library as used by Scipy’s imread. Note that Imageio automatically selects a plugin based on the image to read (unless a format is explicitly specified), but uses Pillow where possible.

In short terms: For images previously read by Scipy’s imread, imageio should generally use Pillow as well, and imageio provides the same functionality as Scipy in these cases. But keep in mind:

  • Instead of mode, use the pilmode keyword argument.
  • Instead of flatten, use the as_gray keyword argument.
  • The documentation for the above arguments is not on imread, but on the docs of the individual formats, e.g. PNG.
  • Imageio’s functions all return numpy arrays, albeit as a subclass (so that meta data can be attached).