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