将加载的 mat 文件转换回 numpy 数组

Convert loaded mat file back to numpy array

我使用 scipy.io.savemat() 将大小为 5000,96,96 的 numpy 数组中的图像保存到 .mat 文件中。

当我想将这些图像加载回 Python 时,我使用 scipy.io.loadmat(),但是,这次它们被放入字典。

如何将它们从 Dictionary 整齐地放入 NumPy 数组?

我正在使用 scipy.io.loadmat 加载 matlab 文件并想将其放入 NumPy 数组中。图像暗淡 = (5000,96,96)

scipy.io.savemat("images.mat")
z = scipy.io.loadmat("images.mat")

NumPy 数组中的图像

根据这个post: 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')])

您有尝试转换的字典条目示例吗?

保存 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