Imported Upstream version 1.25.0
[platform/core/ml/nnfw.git] / compiler / one-cmds / tests / preprocess_images.py
1 # Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import os, shutil, PIL.Image, numpy as np
16
17 input_dir = 'img_files'
18 output_dir = 'raw_files'
19 list_file = 'datalist.txt'
20
21 if os.path.exists(output_dir):
22     shutil.rmtree(output_dir, ignore_errors=True)
23 os.makedirs(output_dir)
24
25 for (root, _, files) in os.walk(input_dir):
26     datalist = open(list_file, 'w')
27     for f in files:
28         with PIL.Image.open(root + '/' + f) as image:
29             # To handle ANTIALIAS deprecation
30             ANTIALIAS = PIL.Image.Resampling.LANCZOS if hasattr(
31                 PIL.Image, "Resampling") else PIL.Image.ANTIALIAS
32
33             img = np.array(image.resize((299, 299), ANTIALIAS)).astype(np.float32)
34             img = ((img / 255) - 0.5) * 2.0
35             output_file = output_dir + '/' + f.replace('jpg', 'data')
36             img.tofile(output_file)
37             datalist.writelines(os.path.abspath(output_file) + '\n')
38     datalist.close()