我使用scipy.io.savemat()
将大小为5000,96,96的numpy数组中的图像保存到.mat文件中。
当我想将这些图像加载到Python中时,我使用scipy.io.loadmat()
,但是,这次它们被放入字典中。
我如何巧妙地将它们从Dictionary转换为NumPy数组?
我正在使用scipy.io.loadmat
加载matlab文件,并希望将其放入NumPy数组中。图像是dims =(5000,96,96)
scipy.io.savemat("images.mat")
z = scipy.io.loadmat("images.mat")
NumPy数组中的图像
保存3d数组:
In [53]: from scipy import io
In [54]: arr = np.arange(8*3*3).reshape(8,3,3)
In [56]: io.savemat('threed.mat',{"a":arr})
加载它:
In [57]: dat = io.loadmat('threed.mat')
In [58]: list(dat.keys())
Out[58]: ['__header__', '__version__', '__globals__', 'a']
按键访问数组(普通字典操作):
In [59]: dat['a'].shape
Out[59]: (8, 3, 3)
In [61]: np.allclose(arr,dat['a'])
Out[61]: True
根据这篇文章:python dict to numpy structured array
将字典转换为numpy数组可以完成如下:
import numpy as np
result = {0: 1.1, 1: 0.7, 2: 0.9, 3: 0.5, 4: 1.0, 5: 0.8, 6: 0.3}
names = ['id','value']
formats = ['int','float']
dtype = dict(names = names, formats=formats)
array = np.array(list(result.items()), dtype=dtype)
print(repr(array))
这导致以下结果:
array([(0, 1.1), (1, 0.7), (2, 0.9), (3, 0.5), (4, 1. ), (5, 0.8),
(6, 0.3)], dtype=[('id', '<i4'), ('value', '<f8')])
你有一个你试图转换的字典条目的例子吗?