AttributeError: module ‘xxx’ has no attribute ‘xxx’
用python时经常会遇到,什么什么库中不存在什么什么方法。百度原因是因为某些问题,该方法在最新版本的库中被移除了,大部分的解决方法是安装其它的辅助库或者升降当前库的版本。这种方法有两个不好之处:
1、调用多个库的时候,往往有几个库对别的库的版本有要求,比如这个tensorflow库对于numpy的版本就有要求。改变后者库版本,可能导致前者的库不能使用。
2、有时候,我们利用在线的IDE跑代码,而我们改变不了IDE的配置,这时这些方法就失效了。
所以,解决的方法是找到能替换的方法。
imread,imsave,imresize
如果在最新版scipy中继续使用这两个函数,会出现如下报错:
AttributeError: module 'scipy.misc' has no attribute 'imread'
AttributeError: module 'scipy.misc' has no attribute 'imsave'
AttributeError: module 'scipy.misc' has no attribute 'imresize'
根据scipy官方文档的说明(20190730):
Functions from scipy.interpolate (spleval, spline, splmake, and spltopp) and functions from scipy.misc (bytescale, fromimage, imfilter, imread, imresize, imrotate, imsave, imshow, toimage) have been removed. The former set has been deprecated since v0.19.0 and the latter has been deprecated since v1.0.0. Similarly, aliases from scipy.misc (comb, factorial, factorial2, factorialk, logsumexp, pade, info, source, who) which have been deprecated since v1.0.0 are removed. SciPy documentation for v1.1.0 can be used to track the new import locations for the relocated functions.
文档中说明了在scipy的0.19.0版本和1.0.0版本中可以用到的imread,imsave,imresize函数在scipy的1.3.0版本中全部被遗弃。
网上对这个问题的解决办法大多数是pip安装PIL或者pillow,不行的话降低scipy的版本。
这并不能解决根本问题,下面给出这三个方法的替代方法:
#imread
#先前版本
img = scipy.misc.imread(image)
#新版本
import imageio
img = imageio.imread(image)
#imsave
#先前版本
scipy.misc.imsave(path, image)
#新版本
import imageio
imageio.imsave(path, image)
#imresize
#先前版本
img = scipy.misc.imresize(image,(IMAGE_H,IMAGE_W))
#新版本
from PIL import Image
img = np.array(Image.fromarray(image).resize((IMAGE_W,IMAGE_H)))