How to convert Matlab Cell Array into Python Numpy Array?
이전 댓글 표시
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.
답변 (1개)
Suvansh Arora
2022년 11월 10일
편집: Suvansh Arora
2022년 11월 10일
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's” built-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.
카테고리
도움말 센터 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!