Skip to content Skip to sidebar Skip to footer

Convert Loaded Mat File Back To Numpy Array

I save images in numpy array of size 5000,96,96 into .mat file using scipy.io.savemat(). When I want to load back these images into Python I use scipy.io.loadmat(), however, this

Solution 1:

Save a 3d array:

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

Load it:

In [57]: dat = io.loadmat('threed.mat')                                         
In [58]: list(dat.keys())                                                       
Out[58]: ['__header__', '__version__', '__globals__', 'a']

Access array by key (normal dictionary action):

In [59]: dat['a'].shape                                                         
Out[59]: (8, 3, 3)
In [61]: np.allclose(arr,dat['a'])                                              
Out[61]: True

Solution 2:

According to this post: python dict to numpy structured array

Coverting a dictionary to a numpy array can be done as follow:

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

This leads to the following result:

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')])

Do you have an example of a dictionary entry you are trying to convert?


Post a Comment for "Convert Loaded Mat File Back To Numpy Array"