How to convert Matlab Cell Array into Python Numpy Array?

191 views (last 30 days)
In matlab, I generate a random number of images, each of the shape (130,100). In this case, the number of images generated was 9. I save them into a cell array like below.
Then, I'd like to import this cell array into python numpy array of the shape (9,130,100). I've tried the following but I get this value error below.
import as sio
import numpy
imgs = sio.loadmat(folder+'/img_array.mat')
ValueError: cannot reshape array of size 9 into shape (9,130,100)
If there's a more efficient way to save these images in matlab (for later converting to numpy arrays), I can do it that way too.

Answers (1)

Suvansh Arora
Suvansh Arora on 10 Nov 2022
Edited: Suvansh Arora on 10 Nov 2022
One of the possible ways is to convert the “cell array” to “double array” and then convert the “double array” to “NumPy array”.
In order to convert your “cell array” to “double array”, please follow the below mentioned ML answers article:
There are couple of ways to convert “double arrays” to “NumPy array”, One method is to use the “NumPy'sbuilt-in method, “asarray:
  • Start by loading your MATLAB “Double array:
myData = eng.eval("load('{}','cluster_class','par')".format('sampleData.mat'))
  • With MATLAB R2022a and later, you can convert MATLAB Double directly to a NumPy array:
a = np.array(myData['cluster_class'])
  • To add additional specification, use MATLAB engine's functions to convert to a Python array with noncomplex(), then to a NumPy array:
a = np.array(myData['cluster_class'].noncomplex().toarray(), 'int')
We use the noncomplex() call to retrieve the data in 1D format (provided it's noncomplex; for complex data, we can use “real() and imag() calls). We also offer the toarray() call to convert a 1D MATLAB “double” into a Python array.array” object.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!