blob: 8cc5295b2c610c35685fb815db3f5a5196c98505 [file] [log] [blame]
Pavel Macenauerd0fedae2020-04-15 14:52:57 +00001# Copyright 2020 NXP
2# SPDX-License-Identifier: MIT
3
4from zipfile import ZipFile
5import numpy as np
6import pyarmnn as ann
7import example_utils as eu
8import os
9
10
11def unzip_file(filename):
12 """Unzips a file to its current location.
13
14 Args:
15 filename (str): Name of the archive.
16
17 Returns:
18 str: Directory path of the extracted files.
19 """
20 with ZipFile(filename, 'r') as zip_obj:
21 zip_obj.extractall(os.path.dirname(filename))
22 return os.path.dirname(filename)
23
24
25if __name__ == "__main__":
26 # Download resources
27 archive_filename = eu.download_file(
28 'https://storage.googleapis.com/download.tensorflow.org/models/tflite/mobilenet_v1_1.0_224_quant_and_labels.zip')
29 dir_path = unzip_file(archive_filename)
30 # names of the files in the archive
31 labels_filename = os.path.join(dir_path, 'labels_mobilenet_quant_v1_224.txt')
32 model_filename = os.path.join(dir_path, 'mobilenet_v1_1.0_224_quant.tflite')
33 kitten_filename = eu.download_file('https://s3.amazonaws.com/model-server/inputs/kitten.jpg')
34
35 # Create a network from the model file
36 net_id, graph_id, parser, runtime = eu.create_tflite_network(model_filename)
37
38 # Load input information from the model
39 # tflite has all the need information in the model unlike other formats
40 input_names = parser.GetSubgraphInputTensorNames(graph_id)
41 assert len(input_names) == 1 # there should be 1 input tensor in mobilenet
42
43 input_binding_info = parser.GetNetworkInputBindingInfo(graph_id, input_names[0])
44 input_width = input_binding_info[1].GetShape()[1]
45 input_height = input_binding_info[1].GetShape()[2]
46
47 # Load output information from the model and create output tensors
48 output_names = parser.GetSubgraphOutputTensorNames(graph_id)
49 assert len(output_names) == 1 # and only one output tensor
50 output_binding_info = parser.GetNetworkOutputBindingInfo(graph_id, output_names[0])
51 output_tensors = ann.make_output_tensors([output_binding_info])
52
53 # Load labels file
54 labels = eu.load_labels(labels_filename)
55
56 # Load images and resize to expected size
57 image_names = [kitten_filename]
58 images = eu.load_images(image_names, input_width, input_height)
59
60 for idx, im in enumerate(images):
61 # Create input tensors
62 input_tensors = ann.make_input_tensors([input_binding_info], [im])
63
64 # Run inference
65 print("Running inference on '{0}' ...".format(image_names[idx]))
66 runtime.EnqueueWorkload(net_id, input_tensors, output_tensors)
67
68 # Process output
69 out_tensor = ann.workload_tensors_to_ndarray(output_tensors)[0][0]
70 results = np.argsort(out_tensor)[::-1]
71 eu.print_top_n(5, results, labels, out_tensor)