H5py将MATLAB Cell对象转化为NumPy矩阵的方法 (Transform MATLAB Cell Object into NumPy matrix by utilizing h5py)

Python 之 h5py 读取 matlab 中 .mat 文件 cell 方法浅析_python 读取mat中的cell-CSDN博客

这篇文章介绍了 1*10 Cell的情况,我提供T*1的情况

我的数据 2588*1,每个Cell是26*26 double:

需要转化为2588*26*26 numpy.ndarray实例

import os
import h5py
import numpy as np

def read_p_same(dir_name: str)
    if os.path.exists(dir_name) == False:
        raise FileNotFoundError

    with h5py.File(dir_name, 'r') as f:
        cell_registered_struct = f['cell_registered_struct']

        for element in cell_registered_struct['p_same_registered_pairs']:
            # !!! The length of element is 2588, 
            # (It only iterates for 1 time, thereby 
            # it's not a real for loop albeit a similar 
            # 'form')
            p_same_single = []
            for i in range(len(element)):
                p_same_single.append(f[element[i]][:])
            p_same = np.stack(p_same_single, axis=0)
            # Now p_same is a numpy.ndarray with a shape of (2588, 26, 26).
    return p_same

# A more concise version
def read_p_same(dir_name: str)
    if os.path.exists(dir_name) == False:
        raise FileNotFoundError

    with h5py.File(dir_name, 'r') as f:
        cell_registered_struct = f['cell_registered_struct']

        for element in cell_registered_struct['p_same_registered_pairs']:
            # !!! The length of element is 2588, 
            # (It only iterates for 1 time, thereby 
            # it's not a real for loop albeit a similar 
            # 'form')
            p_same_single = [f[element[i]][:] for i in range(len(element))]
            p_same = np.stack(p_same_single, axis=0)
            # Now p_same is a numpy.ndarray with a shape of (2588, 26, 26).
    return p_same

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值