reading v 7.3 mat file in python

后端 未结 8 1768
情书的邮戳
情书的邮戳 2020-12-02 09:16

I am trying to read a matlab file with the following code

import scipy.io
mat = scipy.io.loadmat(\'test.mat\')

and it gives me the followin

8条回答
  •  不思量自难忘°
    2020-12-02 09:45

    This function reads Matlab-produced HDF5 .mat files, and returns a structure of nested dicts of Numpy arrays. Matlab writes matrices in Fortran order, so this also transposes matrices and higher-dimensional arrays into conventional Numpy order arr[..., page, row, col].

    import h5py
    
    def read_matlab(filename):
        def conv(path=''):
            p = path or '/'
            paths[p] = ret = {}
            for k, v in f[p].items():
                if type(v).__name__ == 'Group':
                    ret[k] = conv(f'{path}/{k}')  # Nested struct
                    continue
                v = v[()]  # It's a Numpy array now
                if v.dtype == 'object':
                    # HDF5ObjectReferences are converted into a list of actual pointers
                    ret[k] = [r and paths.get(f[r].name, f[r].name) for r in v.flat]
                else:
                    # Matrices and other numeric arrays
                    ret[k] = v if v.ndim < 2 else v.swapaxes(-1, -2)
            return ret
    
        paths = {}
        with h5py.File(filename, 'r') as f:
            return conv()
    

提交回复
热议问题