Publishing 2019 R1 content
[platform/upstream/dldt.git] / inference-engine / ie_bridges / python / sample / classification_sample / classification_sample.py
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 """
- Copyright (c) 2018 Intel Corporation
+ Copyright (C) 2018-2019 Intel Corporation
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
 from __future__ import print_function
 import sys
 import os
-from argparse import ArgumentParser
+from argparse import ArgumentParser, SUPPRESS
 import cv2
 import numpy as np
 import logging as log
@@ -26,22 +26,29 @@ from openvino.inference_engine import IENetwork, IEPlugin
 
 
 def build_argparser():
-    parser = ArgumentParser()
-    parser.add_argument("-m", "--model", help="Path to an .xml file with a trained model.", required=True, type=str)
-    parser.add_argument("-i", "--input", help="Path to a folder with images or path to an image files", required=True,
-                        type=str, nargs="+")
-    parser.add_argument("-l", "--cpu_extension",
-                        help="MKLDNN (CPU)-targeted custom layers.Absolute path to a shared library with the kernels "
-                             "impl.", type=str, default=None)
-    parser.add_argument("-pp", "--plugin_dir", help="Path to a plugin folder", type=str, default=None)
-    parser.add_argument("-d", "--device",
-                        help="Specify the target device to infer on; CPU, GPU, FPGA or MYRIAD is acceptable. Sample "
-                             "will look for a suitable plugin for device specified (CPU by default)", default="CPU",
-                        type=str)
-    parser.add_argument("--labels", help="Labels mapping file", default=None, type=str)
-    parser.add_argument("-nt", "--number_top", help="Number of top results", default=10, type=int)
-    parser.add_argument("-ni", "--number_iter", help="Number of inference iterations", default=1, type=int)
-    parser.add_argument("-pc", "--perf_counts", help="Report performance counters", default=False, action="store_true")
+    parser = ArgumentParser(add_help=False)
+    args = parser.add_argument_group('Options')
+    args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.')
+    args.add_argument("-m", "--model", help="Required. Path to an .xml file with a trained model.", required=True,
+                      type=str)
+    args.add_argument("-i", "--input", help="Required. Path to a folder with images or path to an image files",
+                      required=True,
+                      type=str, nargs="+")
+    args.add_argument("-l", "--cpu_extension",
+                      help="Optional. Required for CPU custom layers. "
+                           "MKLDNN (CPU)-targeted custom layers. Absolute path to a shared library with the"
+                           " kernels implementations.", type=str, default=None)
+    args.add_argument("-pp", "--plugin_dir", help="Optional. Path to a plugin folder", type=str, default=None)
+    args.add_argument("-d", "--device",
+                      help="Optional. Specify the target device to infer on; CPU, GPU, FPGA, HDDL, MYRIAD or HETERO: is "
+                           "acceptable. The sample will look for a suitable plugin for device specified. Default "
+                           "value is CPU",
+                      default="CPU", type=str)
+    args.add_argument("--labels", help="Optional. Path to a labels mapping file", default=None, type=str)
+    args.add_argument("-nt", "--number_top", help="Optional. Number of top results", default=10, type=int)
+    args.add_argument("-ni", "--number_iter", help="Optional. Number of inference iterations", default=1, type=int)
+    args.add_argument("-pc", "--perf_counts", help="Optional. Report performance counters", default=False,
+                      action="store_true")
 
     return parser
 
@@ -93,7 +100,6 @@ def main():
     # Loading model to the plugin
     log.info("Loading model to the plugin")
     exec_net = plugin.load(network=net)
-    del net
 
     # Start sync inference
     log.info("Starting inference ({} iterations)".format(args.number_iter))
@@ -101,7 +107,7 @@ def main():
     for i in range(args.number_iter):
         t0 = time()
         res = exec_net.infer(inputs={input_blob: images})
-        infer_time.append((time()-t0)*1000)
+        infer_time.append((time() - t0) * 1000)
     log.info("Average running time of one iteration: {} ms".format(np.average(np.asarray(infer_time))))
     if args.perf_counts:
         perf_counts = exec_net.requests[0].get_perf_counts()
@@ -120,18 +126,25 @@ def main():
             labels_map = [x.split(sep=' ', maxsplit=1)[-1].strip() for x in f]
     else:
         labels_map = None
+    classid_str = "classid"
+    probability_str = "probability"
     for i, probs in enumerate(res):
         probs = np.squeeze(probs)
         top_ind = np.argsort(probs)[-args.number_top:][::-1]
         print("Image {}\n".format(args.input[i]))
+        print(classid_str, probability_str)
+        print("{} {}".format('-' * len(classid_str), '-' * len(probability_str)))
         for id in top_ind:
-            det_label = labels_map[id] if labels_map else "#{}".format(id)
-            print("{:.7f} label {}".format(probs[id], det_label))
+            det_label = labels_map[id] if labels_map else "{}".format(id)
+            label_length = len(det_label)
+            space_num_before = (len(classid_str) - label_length) // 2
+            space_num_after = len(classid_str) - (space_num_before + label_length) + 2
+            space_num_before_prob = (len(probability_str) - len(str(probs[id]))) // 2
+            print("{}{}{}{}{:.7f}".format(' ' * space_num_before, det_label,
+                                          ' ' * space_num_after, ' ' * space_num_before_prob,
+                                          probs[id]))
         print("\n")
 
-    del exec_net
-    del plugin
-
 
 if __name__ == '__main__':
     sys.exit(main() or 0)