How to convert Matlab Cell Array into Python Numpy Array?

80 Ansichten (letzte 30 Tage)
Rachel Dawn
Rachel Dawn am 7 Nov. 2022
Bearbeitet: Suvansh Arora am 10 Nov. 2022
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 scipy.io as sio
import numpy
imgs = sio.loadmat(folder+'/img_array.mat')
num_imgs=len(imgs['img_array'][0])
img_array=np.array(imgs['img_array'][0])
new_array=img_array.reshape((num_imgs,130,100))
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.

Antworten (1)

Suvansh Arora
Suvansh Arora am 10 Nov. 2022
Bearbeitet: Suvansh Arora am 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.

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by