问题的第一部分。
不要问我为什么,但也许 HDFview 的维护者之一可以站出来。
为了使 HDFview 能够正确显示图像,属性必须是有限长度的字符串才能正确解释。
Use np.string_(<string>)
来自 numpy 包
import h5py
import numpy as np
from PIL import Image
hdf = h5py.File("Sample.h5",'w')
img = Image.open("Image.jpg")
data = np.asarray((img), dtype="uint8")
hdf.create_dataset("Photos/Image 1", data=data, dtype='uint8')
dset = hdf.get("Photos/Image 1")
dset.attrs['CLASS'] = np.string_('IMAGE')
dset.attrs['IMAGE_VERSION'] = np.string_('1.2')
arr = np.asarray([0, 255], dtype=np.uint8)
dset.attrs['IMAGE_MINMAXRANGE'] = list(arr)
dset.attrs['IMAGE_SUBCLASS'] = np.string_('IMAGE_TRUECOLOR')
dset.attrs['INTERLACE_MODE'] = np.string_('INTERLACE_PIXEL')
hdf.close()
This gives in HDFview by double clicking on dataset "Image 1"
第二个问题。
我想你正在使用 PIL 包
功能fromarray
期望“图像模式”参见https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes
在你的情况下是 RBG
所以
import h5py
import numpy as np
from PIL import Image
hdf = h5py.File("Sample.h5",'r')
array = np.array(list(hdf.get("Photos/Image 1")))
img = Image.fromarray(array.astype('uint8'), 'RGB')
img.show()
会给你