数据集.h5格式转彩色.jpg文件

此篇博客介绍了如何使用Python脚本从.h5文件中读取特定组的数组,将其转换为灰度图像,并保存到指定路径。函数`save_image`负责处理RGB组,通过`load_h5`函数加载.h5文件并获取组名。
摘要由CSDN通过智能技术生成
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)

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值