import os
from PIL import Image
import numpy as np
import h5py as h5
# functions
def save_image(file, groups, aim_path, file2):
'''
将.h5/group下的array转换为灰度图像并存储
:param group: .h5文件包中的组名(key值)
:param save_path: 图像存储的路径
:return: None
'''
for group in groups:
if group == 'rgb':
print(group + " 组:")
image_path = aim_path
for i in file[group][:]:
if image_path == "N":
continue
else:
makedir(image_path)
save_path = image_path + file2 + '.jpg'
image = np.array(i)
image *= 255 # 变换为0-255的灰度值
one_sample = file['data'][0, 0] # 加的转换代码
image = Image.fromarray(one_sample[40]).convert('L')
# image = Image.fromarray(image)
image = image.convert('L') # 灰度为L,彩色为RGB’
image.save((save_path))
else:
continue
print("done!")
def makedir(dir_path):
'''
创建文件夹
:param dir_path: 文件夹路径
:return: None
'''
isExists = os.path.exists(dir_path)
if not isExists: # 判断如果文件不存在,则创建
os.makedirs(dir_path)
def load_h5(file_path):
'''
加载.h5数据
:param file_path: .h5文件路径
:return: groups, file
'''
file = h5.File(file_path, "r+")
groups = [key for key in file.keys()]
print("该文件共有以下几组:", groups)
return groups, file
## main
if __name__ == "__main__":
orig_path = '/home/litinglong/~Pycode/HarDNet-MSEG-master/datasets/nyudepthv2/train'
for file1 in os.listdir(orig_path):
aim_path = orig_path+'/'+file1 + '/'
for file2 in os.listdir(aim_path):
last_path = aim_path+'/'+file2
save_path = '/home/litinglong/~Pycode/HarDNet-MSEG-master/dataset/nyudepthv2/train/'
groups, file = load_h5(last_path)
save_image(file, groups, save_path, file2)
数据集.h5格式转彩色.jpg文件
最新推荐文章于 2022-08-23 11:02:59 发布
此篇博客介绍了如何使用Python脚本从.h5文件中读取特定组的数组,将其转换为灰度图像,并保存到指定路径。函数`save_image`负责处理RGB组,通过`load_h5`函数加载.h5文件并获取组名。
摘要由CSDN通过智能技术生成