3 Copyright (C) 2018-2019 Intel Corporation
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
9 http://www.apache.org/licenses/LICENSE-2.0
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.
17 from __future__ import print_function
20 from argparse import ArgumentParser, SUPPRESS
25 from openvino.inference_engine import IENetwork, IEPlugin
28 def build_argparser():
29 parser = ArgumentParser(add_help=False)
30 args = parser.add_argument_group('Options')
31 args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.')
32 args.add_argument("-m", "--model", help="Path to an .xml file with a trained model.", required=True, type=str)
33 args.add_argument("-i", "--input", help="Path to a folder with images or path to an image files", required=True,
35 args.add_argument("-l", "--cpu_extension",
36 help="Optional. Required for CPU custom layers. "
37 "Absolute MKLDNN (CPU)-targeted custom layers. Absolute path to a shared library with the "
38 "kernels implementations", type=str, default=None)
39 args.add_argument("-pp", "--plugin_dir", help="Path to a plugin folder", type=str, default=None)
40 args.add_argument("-d", "--device",
41 help="Specify the target device to infer on; CPU, GPU, FPGA, HDDL or MYRIAD is acceptable. Sample "
42 "will look for a suitable plugin for device specified. Default value is CPU", default="CPU",
44 args.add_argument("-nt", "--number_top", help="Number of top results", default=10, type=int)
45 args.add_argument("-ni", "--number_iter", help="Number of inference iterations", default=1, type=int)
46 args.add_argument("--mean_val_r", "-mean_val_r",
47 help="Mean value of red chanel for mean value subtraction in postprocessing ", default=0,
49 args.add_argument("--mean_val_g", "-mean_val_g",
50 help="Mean value of green chanel for mean value subtraction in postprocessing ", default=0,
52 args.add_argument("--mean_val_b", "-mean_val_b",
53 help="Mean value of blue chanel for mean value subtraction in postprocessing ", default=0,
55 args.add_argument("-pc", "--perf_counts", help="Report performance counters", default=False, action="store_true")
61 log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout)
62 args = build_argparser().parse_args()
63 model_xml = args.model
64 model_bin = os.path.splitext(model_xml)[0] + ".bin"
66 # Plugin initialization for specified device and load extensions library if specified
67 plugin = IEPlugin(device=args.device, plugin_dirs=args.plugin_dir)
68 if args.cpu_extension and 'CPU' in args.device:
69 plugin.add_cpu_extension(args.cpu_extension)
71 log.info("Loading network files:\n\t{}\n\t{}".format(model_xml, model_bin))
72 net = IENetwork(model=model_xml, weights=model_bin)
74 if plugin.device == "CPU":
75 supported_layers = plugin.get_supported_layers(net)
76 not_supported_layers = [l for l in net.layers.keys() if l not in supported_layers]
77 if len(not_supported_layers) != 0:
78 log.error("Following layers are not supported by the plugin for specified device {}:\n {}".
79 format(plugin.device, ', '.join(not_supported_layers)))
80 log.error("Please try to specify cpu extensions library path in sample's command line parameters using -l "
81 "or --cpu_extension command line argument")
84 assert len(net.inputs.keys()) == 1, "Sample supports only single input topologies"
85 assert len(net.outputs) == 1, "Sample supports only single output topologies"
87 log.info("Preparing input blobs")
88 input_blob = next(iter(net.inputs))
89 out_blob = next(iter(net.outputs))
90 net.batch_size = len(args.input)
92 # Read and pre-process input images
93 n, c, h, w = net.inputs[input_blob].shape
94 images = np.ndarray(shape=(n, c, h, w))
96 image = cv2.imread(args.input[i])
97 if image.shape[:-1] != (h, w):
98 log.warning("Image {} is resized from {} to {}".format(args.input[i], image.shape[:-1], (h, w)))
99 image = cv2.resize(image, (w, h))
100 image = image.transpose((2, 0, 1)) # Change data layout from HWC to CHW
102 log.info("Batch size is {}".format(n))
104 # Loading model to the plugin
105 log.info("Loading model to the plugin")
106 exec_net = plugin.load(network=net)
108 # Start sync inference
109 log.info("Starting inference ({} iterations)".format(args.number_iter))
111 for i in range(args.number_iter):
113 res = exec_net.infer(inputs={input_blob: images})
114 infer_time.append((time() - t0) * 1000)
115 log.info("Average running time of one iteration: {} ms".format(np.average(np.asarray(infer_time))))
117 perf_counts = exec_net.requests[0].get_perf_counts()
118 log.info("Performance counters:")
119 print("{:<70} {:<15} {:<15} {:<15} {:<10}".format('name', 'layer_type', 'exet_type', 'status', 'real_time, us'))
120 for layer, stats in perf_counts.items():
121 print("{:<70} {:<15} {:<15} {:<15} {:<10}".format(layer, stats['layer_type'], stats['exec_type'],
122 stats['status'], stats['real_time']))
123 # Processing output blob
124 log.info("Processing output blob")
126 # Post process output
127 for batch, data in enumerate(res):
128 # Clip values to [0, 255] range
129 data = np.swapaxes(data, 0, 2)
130 data = np.swapaxes(data, 0, 1)
131 data = cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
133 data[data > 255] = 255
134 data = data[::] - (args.mean_val_r, args.mean_val_g, args.mean_val_b)
135 out_img = os.path.join(os.path.dirname(__file__), "out_{}.bmp".format(batch))
136 cv2.imwrite(out_img, data)
137 log.info("Result image was saved to {}".format(out_img))
140 if __name__ == '__main__':
141 sys.exit(main() or 0)