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

利用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)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 生成颗粒文件可能需要用到一些特定的库和工具,以下是一种常见的生成颗粒文件的方法: 1. 安装必要的库和工具,如numpy、h5py等。 2. 写一个Python脚本,用于生成颗粒文件。在脚本中,你需要定义颗粒的位置、速度、质量等属性,并将这些属性写入到一个数据结构中。 3. 使用h5py库将数据结构中的属性写入到HDF5格式的文件中。 4. 可以使用其他工具,如OVITO等,来可视化颗粒文件。 以下是一个简单的示例代码,用于生成一个位置为(0, 0, 0)、速度为(1, 1, 1)、质量为1的颗粒,并将其保存到"particles.hdf5"文件中: ``` python import numpy as np import h5py # 定义颗粒属性 position = np.array([[0, 0, 0]]) velocity = np.array([[1, 1, 1]]) mass = np.array([1]) # 将属性写入到数据结构中 data = {'position': position, 'velocity': velocity, 'mass': mass} # 将数据结构写入到HDF5文件中 file = h5py.File('particles.hdf5', 'w') for key in data: file.create_dataset(key, data=data[key]) file.close() ``` 这个示例只是一个简单的例子,实际的颗粒文件可能会包含大量的颗粒和复杂的属性。因此,你需要根据具体的需求来编写生成颗粒文件代码。 ### 回答2: Python可以通过使用相关的库来生成颗粒文件。其中,最常用的库是NumPy,它提供了强大的工具来处理和生成颗粒文件。以下是一种简单的方法: 首先,我们需要导入NumPy库: import numpy as np 然后,我们可以使用NumPy的函数来生成随机的颗粒位置坐标。例如,我们可以使用np.random.uniform函数来生成在给定范围内的随机坐标: positions = np.random.uniform(low=0, high=10, size=(100, 3)) 这将生成一个100个颗粒的颗粒文件,每个颗粒有3个坐标。这些坐标的范围在0到10之间,你可以根据需要进行调整。 接下来,我们可以将生成的颗粒位置保存到一个文件中。例如,我们可以使用NumPy的savetxt函数将其保存为一个文本文件: np.savetxt('particles.txt', positions, fmt='%.4f') 这将创建一个名为"particles.txt"的文件,并将颗粒位置保存在其中。每一行代表一个颗粒,每个坐标值都四舍五入为小数点后4位。 通过这种方法,我们就可以使用Python生成颗粒文件了。当然,你可以根据实际需要自定义文件的格式和内容,这只是一个简单的示例。 ### 回答3: Python生成颗粒文件是指通过使用Python编程语言创建一个包含颗粒信息的文件。颗粒文件通常用于模拟粒子系统、物理引擎或者其他需要模拟大量微小对象的应用程序中。 要创建一个颗粒文件,首先需要确定颗粒的特征和属性。例如,颗粒可以有位置、速度、质量、颜色等属性。然后,可以使用Python中的数据结构(例如列表或字典)来存储每个颗粒的属性。在创建颗粒文件时,可以使用Python文件操作功能将颗粒属性写入到文件中。 下面是一个简单的示例代码,展示了如何使用Python生成颗粒文件: ```python # 颗粒属性示例 particles = [ {"position": (1, 2, 3), "velocity": (0.1, 0.2, 0.3), "mass": 1.0, "color": "red"}, {"position": (4, 5, 6), "velocity": (0.4, 0.5, 0.6), "mass": 2.0, "color": "blue"}, {"position": (7, 8, 9), "velocity": (0.7, 0.8, 0.9), "mass": 0.5, "color": "green"} ] # 生成颗粒文件 with open("particles.txt", "w") as file: for particle in particles: file.write(f"Position: {particle['position']}, Velocity: {particle['velocity']}, Mass: {particle['mass']}, Color: {particle['color']}\n") ``` 在上述示例中,我们定义了一个包含3个颗粒的列表。每个颗粒都有位置、速度、质量和颜色属性。然后,我们使用文件操作功能将颗粒信息写入到名为"particles.txt"的文件中。 通过使用类似的方法,可以根据具体需求生成不同格式的颗粒文件,如CSV、JSON等。这样就可以在其他应用程序中读取颗粒文件,进行模拟、分析或可视化等操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值