利用Python 脚本生成 .h5 文件 代码

本文介绍了一个使用Python脚本批量处理图像并将其存储为.h5文件的方法。该脚本支持多线程处理,能够读取指定目录下的图像文件,调整大小,并将它们存储在一个HDF5文件中,适用于训练feedforward风格迁移模型。

利用Python 脚本生成 .h5 文件 

  1 import os, json, argparse
  2 from threading import Thread
  3 from Queue import Queue
  4 
  5 import numpy as np
  6 from scipy.misc import imread, imresize
  7 import h5py
  8 
  9 """
 10 Create an HDF5 file of images for training a feedforward style transfer model.
 11 """
 12 
 13 parser = argparse.ArgumentParser()
 14 parser.add_argument('--train_dir', default='/media/wangxiao/WangXiao_Dataset/CoCo/train2014')
 15 parser.add_argument('--val_dir', default='/media/wangxiao/WangXiao_Dataset/CoCo/val2014')
 16 parser.add_argument('--output_file', default='/media/wangxiao/WangXiao_Dataset/CoCo/coco-256.h5')
 17 parser.add_argument('--height', type=int, default=256)
 18 parser.add_argument('--width', type=int, default=256)
 19 parser.add_argument('--max_images', type=int, default=-1)
 20 parser.add_argument('--num_workers', type=int, default=2)
 21 parser.add_argument('--include_val', type=int, default=1)
 22 parser.add_argument('--max_resize', default=16, type=int)
 23 args = parser.parse_args()
 24 
 25 
 26 def add_data(h5_file, image_dir, prefix, args):
 27   # Make a list of all images in the source directory
 28   image_list = []
 29   image_extensions = {'.jpg', '.jpeg', '.JPG', '.JPEG', '.png', '.PNG'}
 30   for filename in os.listdir(image_dir):
 31     ext = os.path.splitext(filename)[1]
 32     if ext in image_extensions:
 33       image_list.append(os.path.join(image_dir, filename))
 34   num_images = len(image_list)
 35 
 36   # Resize all images and copy them into the hdf5 file
 37   # We'll bravely try multithreading
 38   dset_name = os.path.join(prefix, 'images')
 39   dset_size = (num_images, 3, args.height, args.width)
 40   imgs_dset = h5_file.create_dataset(dset_name, dset_size, np.uint8)
 41   
 42   # input_queue stores (idx, filename) tuples,
 43   # output_queue stores (idx, resized_img) tuples
 44   input_queue = Queue()
 45   output_queue = Queue()
 46   
 47   # Read workers pull images off disk and resize them
 48   def read_worker():
 49     while True:
 50       idx, filename = input_queue.get()
 51       img = imread(filename)
 52       try:
 53         # First crop the image so its size is a multiple of max_resize
 54         H, W = img.shape[0], img.shape[1]
 55         H_crop = H - H % args.max_resize
 56         W_crop = W - W % args.max_resize
 57         img = img[:H_crop, :W_crop]
 58         img = imresize(img, (args.height, args.width))
 59       except (ValueError, IndexError) as e:
 60         print filename
 61         print img.shape, img.dtype
 62         print e
 63       input_queue.task_done()
 64       output_queue.put((idx, img))
 65   
 66   # Write workers write resized images to the hdf5 file
 67   def write_worker():
 68     num_written = 0
 69     while True:
 70       idx, img = output_queue.get()
 71       if img.ndim == 3:
 72         # RGB image, transpose from H x W x C to C x H x W
 73         imgs_dset[idx] = img.transpose(2, 0, 1)
 74       elif img.ndim == 2:
 75         # Grayscale image; it is H x W so broadcasting to C x H x W will just copy
 76         # grayscale values into all channels.
 77         imgs_dset[idx] = img
 78       output_queue.task_done()
 79       num_written = num_written + 1
 80       if num_written % 100 == 0:
 81         print 'Copied %d / %d images' % (num_written, num_images)
 82   
 83   # Start the read workers.
 84   for i in xrange(args.num_workers):
 85     t = Thread(target=read_worker)
 86     t.daemon = True
 87     t.start()
 88     
 89   # h5py locks internally, so we can only use a single write worker =(
 90   t = Thread(target=write_worker)
 91   t.daemon = True
 92   t.start()
 93     
 94   for idx, filename in enumerate(image_list):
 95     if args.max_images > 0 and idx >= args.max_images: break
 96     input_queue.put((idx, filename))
 97     
 98   input_queue.join()
 99   output_queue.join()
100   
101   
102   
103 if __name__ == '__main__':
104   
105   with h5py.File(args.output_file, 'w') as f:
106     add_data(f, args.train_dir, 'train2014', args)
107 
108     if args.include_val != 0:
109       add_data(f, args.val_dir, 'val2014', args)

 

<think>好的,用户的问题是关于如何将fastMRI解压后的文件转换为.h5格式。首先,我需要回忆一下fastMRI数据集的结构和处理流程。根据之前的知识,fastMRI数据集通常以.zip文件分发,解压后可能包含多个子目录,比如train、valid、test等,每个子目录下可能有多个.h5文件。但用户提到解压后得到的不是.h5文件,可能需要进一步的转换,这可能意味着用户下载的是原始数据还是某种中间格式? 首先,可能需要确认用户下载的数据版本。fastMRI数据集分为单线圈和多线圈两种,但通常提供的已经是.h5格式。如果用户解压后的文件不是.h5,可能是他们下载的是其他格式的数据,或者解压过程中出现了问题。比如,有些数据可能需要使用特定的工具或脚本来处理原始数据(如DICOM或原始k空间数据)转换成.h5格式。 接下来,我需要考虑用户可能的操作步骤。假设用户正确下载了数据集,解压后的文件应该已经是.h5格式。如果用户没有看到.h5文件,可能是因为他们下载了错误的文件,或者解压工具出现问题。例如,在Windows系统下,某些压缩工具可能不支持处理大量的小文件,导致解压不完整。建议用户检查解压后的目录结构,确认是否有文件损坏或未完全解压的情况。 另一种可能性是用户需要自己生成.h5文件,例如从DICOM或其他原始数据转换而来。这种情况下,用户可能需要使用fastMRI提供的脚本或工具。例如,fastMRI的GitHub仓库可能有相关的数据处理脚本,用于将原始数据转换为标准的.h5格式。用户需要按照官方文档的指引,安装必要的依赖库,如h5py,然后运行相应的转换脚本。 此外,还需考虑用户的操作系统环境。例如,在Linux系统下,处理大量文件可能更稳定,而在Windows下可能需要特别注意路径长度限制或权限问题。建议用户确保使用正确的解压工具,如7-Zip或官方推荐的软件,并检查解压后的文件完整性。 如果用户确实需要手动转换其他格式的数据为.h5,可能需要编写Python脚本利用h5py库来创建.h5文件,并将数据按正确的结构存储。但这种情况较为复杂,通常fastMRI数据集已经提供处理好的.h5文件,所以用户可能只是遇到解压问题,而非需要转换格式。 总结来说,用户的问题可能源于解压过程中的错误,或者对数据集结构的误解。需要引导用户检查解压后的文件结构,确认是否使用了正确的数据集版本和解压方法,并参考fastMRI的官方文档或社区资源进行故障排除。</think>以下是关于fastMRI文件解压后转换为.h5文件的逐步说明: 1. **确认原始文件格式**: - fastMRI官方数据集(单线圈/多线圈)原始下载文件.zip格式,解压后应直接生成.h5文件。 - 如果解压后未得到.h5文件,请检查: ✅ 是否下载了正确数据集(knee/skull) ✅ 是否使用完整版数据集(训练集约35GB) 2. **标准解压流程**: ```bash # Linux/macOS 示例 unzip knee_singlecoil_train.zip -d ./fastmri_data/ ``` - 解压后目录结构应包含: ``` fastmri_data/ ├── knee_singlecoil_train/ │ ├── file1001.h5 │ ├── file1002.h5 │ └── ... ``` 3. **异常情况处理**: - **情形1:二次压缩文件**: 若解压后得到新.zip文件,需继续解压: ```bash for file in *.zip; do unzip "$file"; done ``` - **情形2:损坏文件验证**: 通过MD5校验确认完整性: ```bash md5sum *.zip # 与官网提供的校验码对比 ``` 4. **从DICOM转换(高级需求)**: - 仅当处理自定义数据时需要 - 使用fastMRI官方工具: ```python from fastmri.data.subsample import RandomMaskFunc from fastmri.data.transforms to_save_h5 # 需自定义DICOM读取逻辑 ``` 5. **验证.h5文件结构**: ```python import h5py with h5py.File('file1001.h5', 'r') as f: print(f.keys()) # 应显示['kspace', 'reconstruction_rss'] print(f['kspace'].shape) # 应为(切片数, 通道, 高度, 宽度) ``` **注意**:官方数据集不需要额外转换,若流程异常,建议: 1. 重新下载数据集 2. 使用Linux系统处理大文件 3. 参考官方文档(https://fastmri.org/dataset)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值