You need to enable JavaScript to run this app. 如何从FashionGen数据集的h5文件中提取input_image与input_description数据集?
优惠活动
大模型
产品
解决方案
定价
更多

如何从FashionGen数据集的h5文件中提取input_image与input_description数据集?

操作步骤(使用Python h5py库)

首先你需要先安装依赖库:

pip install h5py numpy pillow

你可以根据自己的使用需求选择以下两种提取方式:

方法1:提取后保存为新的h5文件(适合后续批量训练读取)

直接保留原始数据集的结构,仅保留你需要的两个字段,读写效率高:

import h5py

# 定义需要处理的原始文件列表,训练集和验证集文件名替换成你本地的实际文件名
raw_files = [
    "fashiongen_train.h5",
    "fashiongen_val.h5"
]

for file_path in raw_files:
    # 打开原始h5文件,只读模式
    with h5py.File(file_path, "r") as raw_f:
        # 生成新的文件名,比如训练集处理后叫train_extracted.h5
        output_file = file_path.replace(".h5", "_extracted.h5")
        # 创建新的h5文件
        with h5py.File(output_file, "w") as out_f:
            # 复制你需要的两个数据集到新文件
            raw_f.copy("input_image", out_f)
            raw_f.copy("input_description", out_f)
    print(f"{file_path} 处理完成,提取后文件保存为 {output_file}")

方法2:提取为单独的图片文件+对应文本标注(适合可视化、小样本调试)

把每一张图片存为jpg格式,同时生成对应图片文件名和描述的映射csv:

import h5py
import numpy as np
from PIL import Image
import csv
import os

# 分别处理训练集和验证集,这里以训练集为例,验证集替换对应路径即可
raw_file = "fashiongen_train.h5"
save_img_dir = "fashiongen_train_images"
os.makedirs(save_img_dir, exist_ok=True)
annotation_path = "fashiongen_train_annotations.csv"

with h5py.File(raw_file, "r") as f:
    # 获取总样本数
    total_samples = f["input_image"].shape[0]
    # 打开标注文件写入
    with open(annotation_path, "w", encoding="utf-8", newline="") as csv_f:
        writer = csv.writer(csv_f)
        writer.writerow(["image_path", "description"])
        for i in range(total_samples):
            # 读取图片和描述
            img_arr = f["input_image"][i]
            # 原始描述是bytes类型,要转成utf-8字符串
            desc = f["input_description"][i].decode("utf-8")
            # 保存图片
            img_name = f"{i}.jpg"
            img_save_path = os.path.join(save_img_dir, img_name)
            Image.fromarray(img_arr).save(img_save_path)
            # 写入标注
            writer.writerow([img_save_path, desc])
            # 每处理1000条打印进度,不需要可删除
            if (i+1) % 1000 == 0:
                print(f"已处理 {i+1}/{total_samples} 条样本")

注意事项

  • 上述代码的文件名、保存路径都要替换成你本地的实际路径
  • 如果读取h5文件时出现内存不足的问题,不要一次性加载全量数据集,按上述方法逐索引读取即可,h5py支持直接按索引访问不需要全量加载到内存

内容的提问来源于stack exchange,提问作者Mahta Darvish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 12:54:02