保存为 HDF5 的图像未着色

2024-05-18

我目前正在开发一个将文本文件和 jpg 图像转换为 HDF5 格式的程序。用HDFView 3.0打开,似乎图像仅以灰度保存。

hdf = h5py.File("Sample.h5")
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'] = 'IMAGE'
dset.attrs['IMAGE_VERSION'] = '1.2'
arr = np.asarray([0, 255], dtype=np.uint8)
dset.attrs['IMAGE_MINMAXRANGE'] = list(arr)
dset.attrs['IMAGE_SUBCLASS'] = 'IMAGE_TRUECOLOR'
dset.attrs['INTERLACE_MODE'] = 'INTERLACE_PIXEL'

在 python 中,可以使用 Image.show() 方法显示原始彩色图像:

hdf = h5py.File("Sample.h5")
array = np.array(list(hdf.get("Photos/Image 1")))
img = Image.fromarray(array.astype('uint8'))
img.show()

问题的第一部分。

不要问我为什么,但也许 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" my image stored h5 style !

第二个问题。

我想你正在使用 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()

会给你

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

保存为 HDF5 的图像未着色 的相关文章