【解决AttributeError报错】scipy中imresize的替代代码

问题描述

imresize函数可以用来调整图片大小,它的语法是:

B = imresize(A,scale) 
# 返回图像 B,它是将 A 的长宽大小缩放图像 scale 倍之后的图像。输入图像 A 可以是灰度图像、RGB 图像、二值图像或分类图像。
B = imresize(A,(numrows,numcols))
# 返回图像 B,其行数和列数由二元素(numrows,numcols) 指定。
img_resize = imresize(img, float(size) / max(img.shape))

在完成本科毕业设计时,用scipy中的imresize改变图像大小,结果报以下错误:

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

查找scipy官方文档,说明原文如下:

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的版本。但是更改版本有两个弊端:

1.调用多个库的时候,往往有几个库对别的库的版本有要求,比如这个tensorflow库对于numpy的版本就有要求。改变后者库版本,可能导致前者的库不能使用。
2.有时候,我们利用在线的IDE跑代码,而我们改变不了IDE的配置,这时这些方法就失效了。

所以,我们自己编写等价于imresize函数的代码:

#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)))

Image.fromarray:从nparray生成图像,此方法有两个参数:

  • obj (numpy.ndarray): 一个二维numpy数组, 表示要转换为图像的数组。
  • mode (str): 一个字符串, 表示输出图像的模式。

resize:变成指定高宽,此方法有四个参数:

  • InputArray src :输入,原图像,即待改变大小的图像;
  • OutputArray dst: 输出,改变后的图像。和原图像具有相同的内容,只是大小和原图像不一样而已;
  • dsize:输出图像的大小;
  • interpolation:这个是指定插值的方式,图像缩放之后,像素要进行重新计算,靠这个参数来指定重新计算像素的方式;

np.array:再转化成array格式。

img_resize = np.array(Image.fromarray(img).resize(float(size) / max(img.shape)))

猜你喜欢

转载自blog.csdn.net/qq_54708219/article/details/129756578