【问题标题】:Images saved as HDF5 arent colored保存为 HDF5 的图像没有着色
【发布时间】:2019-02-05 17:29:09
【问题描述】:

我目前正在开发一个将文本文件和 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()

【问题讨论】:

  • 如果img.show() 显示彩色图像,基于从hdf 文件加载的数据,则颜色已保存。如果HDFView只显示灰度,那么这是HDFView(或其设置)的问题,而不是文件保存的问题。

标签: python image hdf5 h5py hdf


【解决方案1】:

问题的第一部分。

不要问我为什么,但也许 HDFview 的维护者之一可以站出来。 要使 HDFview 正确显示图像,属性必须是有限长度的字符串才能正确解释。

使用 numpy 包中的 np.string_(<string>)

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()

这通过双击数据集“Image 1”在 HDFview 中给出

第二个问题。

我想你正在使用 PIL 包 函数fromarray 需要“图像的模式”见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()

会给你

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    相关资源
    最近更新 更多