Imported Upstream version 1.7.0
[platform/core/ml/nnfw.git] / compiler / imgdata2hdf5 / imgdata2hdf5.py
1 #!/usr/bin/env python3
2 import h5py as h5
3 import numpy as np
4 import argparse
5 import glob
6 import os
7
8 parser = argparse.ArgumentParser()
9 parser.add_argument(
10     "-l",
11     "--data_list",
12     type=str,
13     help=
14     "Path to the text file which lists the absolute paths of the raw image data files to be converted.",
15     required=True)
16 parser.add_argument(
17     "-o", "--output_path", type=str, help="Path to the output hdf5 file.", required=True)
18
19 args = parser.parse_args()
20 data_list = args.data_list
21 output_path = args.output_path
22
23 # Create h5 file
24 h5_file = h5.File(output_path, 'w')
25 group = h5_file.create_group("value")
26 # We assume the raw input data have the correct type/shape for the corresponding model
27 # If this flag is set in the hdf5 file, record-minmax will skip type/shape check
28 group.attrs['rawData'] = '1'
29
30 if os.path.isfile(data_list) == False:
31     raise SystemExit("No such file. " + data_list)
32
33 # Data list
34 datalist = []
35 with open(data_list, 'r') as f:
36     lines = f.readlines()
37     for line in lines:
38         if line.strip():
39             filename = line.rstrip()
40             if os.path.isfile(filename):
41                 datalist.append(filename)
42             else:
43                 raise SystemExit("No such file. " + filename)
44
45 # Input files
46 num_converted = 0
47 for imgdata in datalist:
48     with open(imgdata, 'rb') as f:
49         sample = group.create_group(str(num_converted))
50         num_converted += 1
51         filename = os.path.basename(imgdata)
52         sample.attrs['desc'] = filename
53         raw_data = bytearray(f.read())
54         # The target model is DNN for handling an input image
55         sample.create_dataset('0', data=raw_data)
56
57 h5_file.close()
58
59 print("Raw image data have been packaged to " + output_path)
60 print("Number of packaged data: " + str(num_converted))