要显示的复杂 h5 文件

complex h5 File to show

我有一个复杂类型的 h5 文件。二维数组。我想展示它。但是我有以下错误。怎么了?

import h5py 
import numpy as np 
import matplotlib.pyplot as plt

with h5py.File('obj_0001.h5', 'r') as hdf:
    ls = list(hdf.keys())
    print('List of datasets in thies file: \n', ls)
    data = hdf.get('dataset')

    diff = np.array(data)
    print('Shape of dataset: \n', diff.shape)

plt.figure(1)
plt.imshow(np.abs(diff))
plt.savefig('diff_test.png')
plt.show()
UFuncTypeError: ufunc 'absolute' did not contain a loop with signature matching types dtype([('real', '<f4'), ('imag', '<f4')]) -> dtype([('real', '<f4'), ('imag', '<f4')])

根据http://docs.h5py.org/en/stable/faq.html#what-datatypes-are-supported

h5py支持复杂的dtype,代表一个HDF5 struc.

错误表明 diff.dtypedtype([('real', '<f4'), ('imag', '<f4')])。我不知道这是您 np.array(data) 转换的结果,还是数据在文件中的存储方式有所不同。

diff = data[:]

可能值得一试,因为这是从数据集中加载数组的首选语法。

但是如果 diff 是那个结构化数组,你可以创建一个复杂的数据类型:

In [303]: arr2 = np.ones((3,), np.dtype([('real','f'),('imag','f')]))                                  
In [304]: arr2                                                                                         
Out[304]: 
array([(1., 1.), (1., 1.), (1., 1.)],
      dtype=[('real', '<f4'), ('imag', '<f4')])
In [305]: arr3 = arr2['real']+1j*arr2['imag']                                                          
In [306]: arr3                                                                                         
Out[306]: array([1.+1.j, 1.+1.j, 1.+1.j], dtype=complex64)

abs 进行测试:

In [307]: np.abs(arr2)                                                                                 
---------------------------------------------------------------------------
UFuncTypeError                            Traceback (most recent call last)
<ipython-input-307-333e28818b26> in <module>
----> 1 np.abs(arr2)

UFuncTypeError: ufunc 'absolute' did not contain a loop with signature matching types dtype([('real', '<f4'), ('imag', '<f4')]) -> dtype([('real', '<f4'), ('imag', '<f4')])
In [308]: np.abs(arr3)                                                                                 
Out[308]: array([1.4142135, 1.4142135, 1.4142135], dtype=float32)