Reputation: 147
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 time they are put into dictionary.
How can I neatly put them from Dictionary to NumPy array?
I am using the scipy.io.loadmat
to load matlab file and want to put it in NumPy array. The images are of dims = (5000,96,96)
scipy.io.savemat("images.mat")
z = scipy.io.loadmat("images.mat")
images in NumPy array
Upvotes: 2
Views: 2808
Reputation: 231665
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
Upvotes: 2
Reputation: 63
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?
Upvotes: -1