Matlab写入H5文件后Python(h5py)读取轴顺序变化问题
This boils down to a core difference in array storage conventions between MATLAB and Python (including h5py), and how each tool interacts with the HDF5 standard:
1. MATLAB uses column-major order, h5py uses row-major
MATLAB is built around column-major (Fortran-style) array storage, while Python (and most C-based tools like h5py) uses row-major (C-style). HDF5 itself follows row-major order, but MATLAB automatically adjusts for this mismatch during write/read operations:
- When you save your
64×64×3×4array to HDF5 in MATLAB, it internally transposes the dimensions to4×3×64×64to align with HDF5's storage rules. - When you read the file back in MATLAB, it quietly transposes the dimensions again to restore your original
64×64×3×4shape—this happens behind the scenes, so you never see the transposed version.
2. Confirm with HDF5 metadata
If you run h5disp('data.h5') in MATLAB, you’ll see the actual stored dimensions of /Image are 4×3×64×64. h5py reads the file exactly as it’s stored, so it returns that shape directly without any automatic adjustment.
3. Fix the shape in Python
To get the same dimension order as MATLAB, just transpose the array after reading it with h5py. For your specific case, you can explicitly map the axes to reverse the transposition:
import h5py hf = h5py.File('./data.h5', 'r') syn1 = hf['/Image'][()] # Read the dataset into a NumPy array # Convert 4×3×64×64 back to 64×64×3×4 syn1_corrected = syn1.transpose((2, 3, 1, 0))
This will give you an array with the exact dimension order you had in MATLAB.
内容的提问来源于stack exchange,提问作者bhushan23

