保存array格式数据成灰度图片,出现AttributeError: module 'scipy' has no attribute 'misc' 错误完美解决方案

前言

最近跑时间序列模型,output和label全都没问题, 准备把对应的batchsize的step图片保存在一起对比来看。这里刚开始使用scipy,但出现了 AttributeError: module ‘scipy’ has no attribute 'misc’ error

scipy

大概是下面这种的代码
temp为一个三维的array数据这里为 (128, 640, 1),说白了就是个长宽为128乘以640的一个channel为1的灰度图片

import scipy
scipy.misc.toimage(temp * 255, high=255, low=0, cmin=0, cmax=255).save(
            os.path.join(result_dir, 'train_%d.jpg' % (indp)))

但是报错,后来一查才知道:
在这里插入图片描述
在1.2.0之后已经被deprecated。
我查了一下我的版本是,1.3.0.

解决方案

本来心思 下个低版本的scipy,但发现直接pip install scipy==0.18.1报错,从网上直接下载安装文件还没有了,看来还是换一个来做才是正道,所以我找到了PIL,这个python图像库

from PIL import Image
Image.fromarray((temp * 256).astype(np.uint8)).save(os.path.join(result_dir, 'train_%d.jpg' % (indp)))

但报错了
KeyError: ((1, 1, 1), ‘|u1’)
保存array格式数据成灰度图片,出现AttributeError: module 'scipy' has no attribute 'misc' 错误完美解决方案_第1张图片
经过分析才知道
Image.fromarray()的输入为三个shape,并且最后一个维度一定是3,因为这个保存的是灰度的,所以这里我们往 灰度想。

查了一下这个函数。

Image.fromarray((temp * 256).astype(np.uint8), mode='L').save(os.path.join(result_dir, 'train_%d.jpg' % (indp)))

这样输入即为gray图像(model=‘L’)

但还是报错了
在这里插入图片描述
为啥呢?
当然了,灰度图像的最后一个维度的channel其实可以直接squeese掉啊。。
这样输入就不是 (128, 640, 1)而是 (128, 640)

最后解决代码为

 temp = np.squeeze(temp, axis=2)
 Image.fromarray((temp * 256).astype(np.uint8), mode='L').save(os.path.join(result_dir, 'train_%d.jpg' % (indp)))

你可能感兴趣的:(CV)