test_tf.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. if 'exclude' in net_meta.keys() and net_meta['exclude'] is True:
  21. continue
  22. print("Testing %s" % net_name)
  23. with open(net_meta['frozen_graph_filename'], 'rb') as f:
  24. graph_def = tf.GraphDef()
  25. graph_def.ParseFromString(f.read())
  26. with tf.Graph().as_default() as graph:
  27. tf.import_graph_def(graph_def, name="")
  28. tf_config = tf.ConfigProto()
  29. tf_config.gpu_options.allow_growth = True
  30. tf_config.allow_soft_placement = True
  31. with tf.Session(config=tf_config, graph=graph) as tf_sess:
  32. tf_input = tf_sess.graph.get_tensor_by_name(net_meta['input_name'] + ':0')
  33. tf_output = tf_sess.graph.get_tensor_by_name(net_meta['output_names'][0] + ':0')
  34. # load and preprocess image
  35. image = cv2.imread(TEST_IMAGE_PATH)
  36. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  37. image = cv2.resize(image, (net_meta['input_width'], net_meta['input_height']))
  38. image = net_meta['preprocess_fn'](image)
  39. # run network
  40. times = []
  41. for i in range(NUM_RUNS + 1):
  42. t0 = time.time()
  43. output = tf_sess.run([tf_output], feed_dict={
  44. tf_input: image[None, ...]
  45. })[0]
  46. t1 = time.time()
  47. times.append(1000 * (t1 - t0))
  48. avg_time = np.mean(times[1:]) # don't include first run
  49. # parse output
  50. top5 = net_meta['postprocess_fn'](output)
  51. print(top5)
  52. test_f.write("%s %s\n" % (net_name, avg_time))