Add a section of how to link IE with CMake project (#99)
[platform/upstream/dldt.git] / inference-engine / ie_bridges / python / sample / classification_sample_async.py
1 #!/usr/bin/env python
2 """
3  Copyright (c) 2018 Intel Corporation
4
5  Licensed under the Apache License, Version 2.0 (the "License");
6  you may not use this file except in compliance with the License.
7  You may obtain a copy of the License at
8
9       http://www.apache.org/licenses/LICENSE-2.0
10
11  Unless required by applicable law or agreed to in writing, software
12  distributed under the License is distributed on an "AS IS" BASIS,
13  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  See the License for the specific language governing permissions and
15  limitations under the License.
16 """
17 from __future__ import print_function
18 import sys
19 import os
20 from argparse import ArgumentParser
21 import cv2
22 import numpy as np
23 import logging as log
24 from time import time
25 from openvino.inference_engine import IENetwork, IEPlugin
26
27
28 def build_argparser():
29     parser = ArgumentParser()
30     parser.add_argument("-m", "--model", help="Path to an .xml file with a trained model.", required=True, type=str)
31     parser.add_argument("-i", "--input", help="Path to a folder with images or path to an image files", required=True,
32                         type=str, nargs="+")
33     parser.add_argument("-l", "--cpu_extension",
34                         help="MKLDNN (CPU)-targeted custom layers.Absolute path to a shared library with the kernels "
35                              "impl.", type=str, default=None)
36     parser.add_argument("-pp", "--plugin_dir", help="Path to a plugin folder", type=str, default=None)
37     parser.add_argument("-d", "--device",
38                         help="Specify the target device to infer on; CPU, GPU, FPGA or MYRIAD is acceptable. Sample "
39                              "will look for a suitable plugin for device specified (CPU by default)", default="CPU",
40                         type=str)
41     parser.add_argument("--labels", help="Labels mapping file", default=None, type=str)
42     parser.add_argument("-nt", "--number_top", help="Number of top results", default=10, type=int)
43     parser.add_argument("-ni", "--number_iter", help="Number of inference iterations", default=1, type=int)
44     parser.add_argument("-pc", "--perf_counts", help="Report performance counters", default=False, action="store_true")
45
46     return parser
47
48
49 def main():
50     log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout)
51     args = build_argparser().parse_args()
52     model_xml = args.model
53     model_bin = os.path.splitext(model_xml)[0] + ".bin"
54
55     # Plugin initialization for specified device and load extensions library if specified
56     plugin = IEPlugin(device=args.device, plugin_dirs=args.plugin_dir)
57     if args.cpu_extension and 'CPU' in args.device:
58         plugin.add_cpu_extension(args.cpu_extension)
59     # Read IR
60     log.info("Loading network files:\n\t{}\n\t{}".format(model_xml, model_bin))
61     net = IENetwork(model=model_xml, weights=model_bin)
62
63     if plugin.device == "CPU":
64         supported_layers = plugin.get_supported_layers(net)
65         not_supported_layers = [l for l in net.layers.keys() if l not in supported_layers]
66         if len(not_supported_layers) != 0:
67             log.error("Following layers are not supported by the plugin for specified device {}:\n {}".
68                       format(plugin.device, ', '.join(not_supported_layers)))
69             log.error("Please try to specify cpu extensions library path in sample's command line parameters using -l "
70                       "or --cpu_extension command line argument")
71             sys.exit(1)
72     assert len(net.inputs.keys()) == 1, "Sample supports only single input topologies"
73     assert len(net.outputs) == 1, "Sample supports only single output topologies"
74
75     log.info("Preparing input blobs")
76     input_blob = next(iter(net.inputs))
77     out_blob = next(iter(net.outputs))
78     net.batch_size = len(args.input)
79
80     # Read and pre-process input images
81     n, c, h, w = net.inputs[input_blob].shape
82     images = np.ndarray(shape=(n, c, h, w))
83     for i in range(n):
84         image = cv2.imread(args.input[i])
85         if image.shape[:-1] != (h, w):
86             log.warning("Image {} is resized from {} to {}".format(args.input[i], image.shape[:-1], (h, w)))
87             image = cv2.resize(image, (w, h))
88         image = image.transpose((2, 0, 1))  # Change data layout from HWC to CHW
89         images[i] = image
90     log.info("Batch size is {}".format(n))
91
92     # Loading model to the plugin
93     log.info("Loading model to the plugin")
94     exec_net = plugin.load(network=net)
95     del net
96
97     # Start sync inference
98     log.info("Starting inference ({} iterations)".format(args.number_iter))
99     infer_time = []
100     for i in range(args.number_iter):
101         t0 = time()
102         infer_request_handle = exec_net.start_async(request_id=0, inputs={input_blob: images})
103         infer_request_handle.wait()
104         infer_time.append((time() - t0) * 1000)
105     log.info("Average running time of one iteration: {} ms".format(np.average(np.asarray(infer_time))))
106     if args.perf_counts:
107         perf_counts = infer_request_handle.get_perf_counts()
108         log.info("Performance counters:")
109         print("{:<70} {:<15} {:<15} {:<15} {:<10}".format('name', 'layer_type', 'exet_type', 'status', 'real_time, us'))
110         for layer, stats in perf_counts.items():
111             print("{:<70} {:<15} {:<15} {:<15} {:<10}".format(layer, stats['layer_type'], stats['exec_type'],
112                                                               stats['status'], stats['real_time']))
113     # Processing output blob
114     log.info("Processing output blob")
115     res = infer_request_handle.outputs[out_blob]
116     log.info("Top {} results: ".format(args.number_top))
117     if args.labels:
118         with open(args.labels, 'r') as f:
119             labels_map = [x.split(sep=' ', maxsplit=1)[-1].strip() for x in f]
120     else:
121         labels_map = None
122     for i, probs in enumerate(res):
123         probs = np.squeeze(probs)
124         top_ind = np.argsort(probs)[-args.number_top:][::-1]
125         print("Image {}\n".format(args.input[i]))
126         for id in top_ind:
127             det_label = labels_map[id] if labels_map else "#{}".format(id)
128             print("{:.7f} {}".format(probs[id], det_label))
129         print("\n")
130
131     del exec_net
132     del plugin
133
134
135 if __name__ == '__main__':
136     sys.exit(main() or 0)