test_tf.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  2. # Full license terms provided in LICENSE.md file.
  3. import sys
  4. sys.path.append('third_party/models/')
  5. sys.path.append('third_party/models/research')
  6. sys.path.append('third_party/models/research/slim')
  7. #from PIL import Image
  8. #import matplotlib.pyplot as plt
  9. import numpy as np
  10. import tensorflow as tf
  11. from model_meta import NETS, FROZEN_GRAPHS_DIR, CHECKPOINT_DIR
  12. import time
  13. import cv2
  14. TEST_IMAGE_PATH='data/images/gordon_setter.jpg'
  15. TEST_OUTPUT_PATH='data/test_output_tf.txt'
  16. NUM_RUNS=50
  17. if __name__ == '__main__':
  18. with open(TEST_OUTPUT_PATH, 'w') as test_f:
  19. for net_name, net_meta in NETS.items():
  20. print("Testing %s" % net_name)
  21. with open(net_meta['frozen_graph_filename'], 'rb') as f:
  22. graph_def = tf.GraphDef()
  23. graph_def.ParseFromString(f.read())
  24. with tf.Graph().as_default() as graph:
  25. tf.import_graph_def(graph_def, name="")
  26. tf_config = tf.ConfigProto()
  27. tf_config.gpu_options.allow_growth = True
  28. tf_config.allow_soft_placement = True
  29. tf_sess = tf.Session(config=tf_config, graph=graph)
  30. tf_input = tf_sess.graph.get_tensor_by_name(net_meta['input_name'] + ':0')
  31. tf_output = tf_sess.graph.get_tensor_by_name(net_meta['output_names'][0] + ':0')
  32. # load and preprocess image
  33. image = cv2.imread(TEST_IMAGE_PATH)
  34. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  35. image = cv2.resize(image, (net_meta['input_width'], net_meta['input_height']))
  36. image = net_meta['preprocess_fn'](image)
  37. # run network
  38. times = []
  39. for i in range(NUM_RUNS + 1):
  40. t0 = time.time()
  41. output = tf_sess.run([tf_output], feed_dict={
  42. tf_input: image[None, ...]
  43. })[0]
  44. t1 = time.time()
  45. times.append(1000 * (t1 - t0))
  46. avg_time = np.mean(times[1:]) # don't include first run
  47. # parse output
  48. top5 = net_meta['postprocess_fn'](output)
  49. print(top5)
  50. test_f.write("%s %s\n" % (net_name, avg_time))