【解决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)))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北京地铁1号线

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值