Skip to content

Instantly share code, notes, and snippets.

@iaalm
Created October 18, 2018 06:50
Show Gist options
  • Save iaalm/fc4133707a33c99c693408c304d426bd to your computer and use it in GitHub Desktop.
Save iaalm/fc4133707a33c99c693408c304d426bd to your computer and use it in GitHub Desktop.
Convert between .mat and .h5
#!/usr/bin/python3
import h5py
import numpy
import scipy.io
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("file", help="h5 file or mat file")
args = parser.parse_args()
data = {}
if args.file.endswith('.h5'):
with h5py.File(args.file) as fd:
for i in fd.keys():
data[i] = fd[i][...]
scipy.io.savemat(args.file[:-3] + '.mat', data)
elif args.file.endswith('.mat'):
data = scipy.io.loadmat(args.file)
with h5py.File(args.file[:-4] + '.h5', 'w') as fd:
for i in data.keys():
if i not in ['__globals__', '__header__', '__version__']:
fd[i] = numpy.squeeze(data[i])
else:
raise ValueError('filename must ends with .h5 or .mat')
@sagorbrur
Copy link

Hi, thanks for this gist.
while compiling this code I am getting error.(below-error-log).

python convert-mat.py SynthText.h5

<KeysViewHDF5 ['data']>
Traceback (most recent call last):
  File "convert-mat.py", line 17, in <module>
    data[i] = fd[i][...]
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "/home/sagor/anaconda3/envs/tf3/lib/python3.6/site-packages/h5py/_hl/group.py", line 262, in __getitem__
    oid = h5o.open(self.id, self._e(name), lapl=self._lapl)
  File "/home/sagor/anaconda3/envs/tf3/lib/python3.6/site-packages/h5py/_hl/base.py", line 137, in _e
    name = name.encode('ascii')
AttributeError: 'ellipsis' object has no attribute 'encode'

Would you please help to solve this problem.

@DorisED
Copy link

DorisED commented Sep 30, 2020

I got the same error! I would be greatful if you could post a solution.
Thanks so much.

@AgriPooja
Copy link

Hello,
when i run
python convert.py trainedNet.mat
it converts the file into trainedNet.h5 but is it a correct conversion?
as i am getting error:

tid = h5t.py_create(dtype, logical=1)
  File "h5py\h5t.pyx", line 1634, in h5py.h5t.py_create
  File "h5py\h5t.pyx", line 1656, in h5py.h5t.py_create
  File "h5py\h5t.pyx", line 1678, in h5py.h5t.py_create
  File "h5py\h5t.pyx", line 1591, in h5py.h5t._c_compound
  File "h5py\h5t.pyx", line 1656, in h5py.h5t.py_create
  File "h5py\h5t.pyx", line 1711, in h5py.h5t.py_create
TypeError: Object dtype dtype('O') has no native HDF5 equivalent

please resolve this issue

@iaalm
Copy link
Author

iaalm commented Jun 24, 2023

Hi @AgriPooja , is it possible to share you .mat files? I can have a try with it.

@AgriPooja
Copy link

Hello, i am not able to share the .mat files here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment