You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1004 lines
48 KiB

6 years ago
  1. # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Tests for object_detection.export_inference_graph."""
  16. import os
  17. import numpy as np
  18. import six
  19. import tensorflow as tf
  20. from google.protobuf import text_format
  21. from tensorflow.python.framework import dtypes
  22. from tensorflow.python.ops import array_ops
  23. from object_detection import exporter
  24. from object_detection.builders import graph_rewriter_builder
  25. from object_detection.builders import model_builder
  26. from object_detection.core import model
  27. from object_detection.protos import graph_rewriter_pb2
  28. from object_detection.protos import pipeline_pb2
  29. from object_detection.utils import ops
  30. if six.PY2:
  31. import mock # pylint: disable=g-import-not-at-top
  32. else:
  33. from unittest import mock # pylint: disable=g-import-not-at-top
  34. slim = tf.contrib.slim
  35. class FakeModel(model.DetectionModel):
  36. def __init__(self, add_detection_keypoints=False, add_detection_masks=False):
  37. self._add_detection_keypoints = add_detection_keypoints
  38. self._add_detection_masks = add_detection_masks
  39. def preprocess(self, inputs):
  40. true_image_shapes = [] # Doesn't matter for the fake model.
  41. return tf.identity(inputs), true_image_shapes
  42. def predict(self, preprocessed_inputs, true_image_shapes):
  43. return {'image': tf.layers.conv2d(preprocessed_inputs, 3, 1)}
  44. def postprocess(self, prediction_dict, true_image_shapes):
  45. with tf.control_dependencies(prediction_dict.values()):
  46. postprocessed_tensors = {
  47. 'detection_boxes': tf.constant([[[0.0, 0.0, 0.5, 0.5],
  48. [0.5, 0.5, 0.8, 0.8]],
  49. [[0.5, 0.5, 1.0, 1.0],
  50. [0.0, 0.0, 0.0, 0.0]]], tf.float32),
  51. 'detection_scores': tf.constant([[0.7, 0.6],
  52. [0.9, 0.0]], tf.float32),
  53. 'detection_classes': tf.constant([[0, 1],
  54. [1, 0]], tf.float32),
  55. 'num_detections': tf.constant([2, 1], tf.float32),
  56. 'raw_detection_boxes': tf.constant([[[0.0, 0.0, 0.5, 0.5],
  57. [0.5, 0.5, 0.8, 0.8]],
  58. [[0.5, 0.5, 1.0, 1.0],
  59. [0.0, 0.5, 0.0, 0.5]]],
  60. tf.float32),
  61. 'raw_detection_scores': tf.constant([[0.7, 0.6],
  62. [0.9, 0.5]], tf.float32),
  63. }
  64. if self._add_detection_keypoints:
  65. postprocessed_tensors['detection_keypoints'] = tf.constant(
  66. np.arange(48).reshape([2, 2, 6, 2]), tf.float32)
  67. if self._add_detection_masks:
  68. postprocessed_tensors['detection_masks'] = tf.constant(
  69. np.arange(64).reshape([2, 2, 4, 4]), tf.float32)
  70. return postprocessed_tensors
  71. def restore_map(self, checkpoint_path, fine_tune_checkpoint_type):
  72. pass
  73. def loss(self, prediction_dict, true_image_shapes):
  74. pass
  75. def regularization_losses(self):
  76. pass
  77. def updates(self):
  78. pass
  79. class ExportInferenceGraphTest(tf.test.TestCase):
  80. def _save_checkpoint_from_mock_model(self,
  81. checkpoint_path,
  82. use_moving_averages,
  83. enable_quantization=False):
  84. g = tf.Graph()
  85. with g.as_default():
  86. mock_model = FakeModel()
  87. preprocessed_inputs, true_image_shapes = mock_model.preprocess(
  88. tf.placeholder(tf.float32, shape=[None, None, None, 3]))
  89. predictions = mock_model.predict(preprocessed_inputs, true_image_shapes)
  90. mock_model.postprocess(predictions, true_image_shapes)
  91. if use_moving_averages:
  92. tf.train.ExponentialMovingAverage(0.0).apply()
  93. tf.train.get_or_create_global_step()
  94. if enable_quantization:
  95. graph_rewriter_config = graph_rewriter_pb2.GraphRewriter()
  96. graph_rewriter_config.quantization.delay = 500000
  97. graph_rewriter_fn = graph_rewriter_builder.build(
  98. graph_rewriter_config, is_training=False)
  99. graph_rewriter_fn()
  100. saver = tf.train.Saver()
  101. init = tf.global_variables_initializer()
  102. with self.test_session() as sess:
  103. sess.run(init)
  104. saver.save(sess, checkpoint_path)
  105. def _load_inference_graph(self, inference_graph_path, is_binary=True):
  106. od_graph = tf.Graph()
  107. with od_graph.as_default():
  108. od_graph_def = tf.GraphDef()
  109. with tf.gfile.GFile(inference_graph_path) as fid:
  110. if is_binary:
  111. od_graph_def.ParseFromString(fid.read())
  112. else:
  113. text_format.Parse(fid.read(), od_graph_def)
  114. tf.import_graph_def(od_graph_def, name='')
  115. return od_graph
  116. def _create_tf_example(self, image_array):
  117. with self.test_session():
  118. encoded_image = tf.image.encode_jpeg(tf.constant(image_array)).eval()
  119. def _bytes_feature(value):
  120. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
  121. example = tf.train.Example(features=tf.train.Features(feature={
  122. 'image/encoded': _bytes_feature(encoded_image),
  123. 'image/format': _bytes_feature('jpg'),
  124. 'image/source_id': _bytes_feature('image_id')
  125. })).SerializeToString()
  126. return example
  127. def test_export_graph_with_image_tensor_input(self):
  128. tmp_dir = self.get_temp_dir()
  129. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  130. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  131. use_moving_averages=False)
  132. with mock.patch.object(
  133. model_builder, 'build', autospec=True) as mock_builder:
  134. mock_builder.return_value = FakeModel()
  135. output_directory = os.path.join(tmp_dir, 'output')
  136. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  137. pipeline_config.eval_config.use_moving_averages = False
  138. exporter.export_inference_graph(
  139. input_type='image_tensor',
  140. pipeline_config=pipeline_config,
  141. trained_checkpoint_prefix=trained_checkpoint_prefix,
  142. output_directory=output_directory)
  143. self.assertTrue(os.path.exists(os.path.join(
  144. output_directory, 'saved_model', 'saved_model.pb')))
  145. def test_write_inference_graph(self):
  146. tmp_dir = self.get_temp_dir()
  147. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  148. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  149. use_moving_averages=False)
  150. with mock.patch.object(
  151. model_builder, 'build', autospec=True) as mock_builder:
  152. mock_builder.return_value = FakeModel()
  153. output_directory = os.path.join(tmp_dir, 'output')
  154. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  155. pipeline_config.eval_config.use_moving_averages = False
  156. exporter.export_inference_graph(
  157. input_type='image_tensor',
  158. pipeline_config=pipeline_config,
  159. trained_checkpoint_prefix=trained_checkpoint_prefix,
  160. output_directory=output_directory,
  161. write_inference_graph=True)
  162. self.assertTrue(os.path.exists(os.path.join(
  163. output_directory, 'inference_graph.pbtxt')))
  164. def test_export_graph_with_fixed_size_image_tensor_input(self):
  165. input_shape = [1, 320, 320, 3]
  166. tmp_dir = self.get_temp_dir()
  167. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  168. self._save_checkpoint_from_mock_model(
  169. trained_checkpoint_prefix, use_moving_averages=False)
  170. with mock.patch.object(
  171. model_builder, 'build', autospec=True) as mock_builder:
  172. mock_builder.return_value = FakeModel()
  173. output_directory = os.path.join(tmp_dir, 'output')
  174. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  175. pipeline_config.eval_config.use_moving_averages = False
  176. exporter.export_inference_graph(
  177. input_type='image_tensor',
  178. pipeline_config=pipeline_config,
  179. trained_checkpoint_prefix=trained_checkpoint_prefix,
  180. output_directory=output_directory,
  181. input_shape=input_shape)
  182. saved_model_path = os.path.join(output_directory, 'saved_model')
  183. self.assertTrue(
  184. os.path.exists(os.path.join(saved_model_path, 'saved_model.pb')))
  185. with tf.Graph().as_default() as od_graph:
  186. with self.test_session(graph=od_graph) as sess:
  187. meta_graph = tf.saved_model.loader.load(
  188. sess, [tf.saved_model.tag_constants.SERVING], saved_model_path)
  189. signature = meta_graph.signature_def['serving_default']
  190. input_tensor_name = signature.inputs['inputs'].name
  191. image_tensor = od_graph.get_tensor_by_name(input_tensor_name)
  192. self.assertSequenceEqual(image_tensor.get_shape().as_list(),
  193. input_shape)
  194. def test_export_graph_with_tf_example_input(self):
  195. tmp_dir = self.get_temp_dir()
  196. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  197. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  198. use_moving_averages=False)
  199. with mock.patch.object(
  200. model_builder, 'build', autospec=True) as mock_builder:
  201. mock_builder.return_value = FakeModel()
  202. output_directory = os.path.join(tmp_dir, 'output')
  203. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  204. pipeline_config.eval_config.use_moving_averages = False
  205. exporter.export_inference_graph(
  206. input_type='tf_example',
  207. pipeline_config=pipeline_config,
  208. trained_checkpoint_prefix=trained_checkpoint_prefix,
  209. output_directory=output_directory)
  210. self.assertTrue(os.path.exists(os.path.join(
  211. output_directory, 'saved_model', 'saved_model.pb')))
  212. def test_export_graph_with_encoded_image_string_input(self):
  213. tmp_dir = self.get_temp_dir()
  214. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  215. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  216. use_moving_averages=False)
  217. with mock.patch.object(
  218. model_builder, 'build', autospec=True) as mock_builder:
  219. mock_builder.return_value = FakeModel()
  220. output_directory = os.path.join(tmp_dir, 'output')
  221. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  222. pipeline_config.eval_config.use_moving_averages = False
  223. exporter.export_inference_graph(
  224. input_type='encoded_image_string_tensor',
  225. pipeline_config=pipeline_config,
  226. trained_checkpoint_prefix=trained_checkpoint_prefix,
  227. output_directory=output_directory)
  228. self.assertTrue(os.path.exists(os.path.join(
  229. output_directory, 'saved_model', 'saved_model.pb')))
  230. def _get_variables_in_checkpoint(self, checkpoint_file):
  231. return set([
  232. var_name
  233. for var_name, _ in tf.train.list_variables(checkpoint_file)])
  234. def test_replace_variable_values_with_moving_averages(self):
  235. tmp_dir = self.get_temp_dir()
  236. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  237. new_checkpoint_prefix = os.path.join(tmp_dir, 'new.ckpt')
  238. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  239. use_moving_averages=True)
  240. graph = tf.Graph()
  241. with graph.as_default():
  242. fake_model = FakeModel()
  243. preprocessed_inputs, true_image_shapes = fake_model.preprocess(
  244. tf.placeholder(dtype=tf.float32, shape=[None, None, None, 3]))
  245. predictions = fake_model.predict(preprocessed_inputs, true_image_shapes)
  246. fake_model.postprocess(predictions, true_image_shapes)
  247. exporter.replace_variable_values_with_moving_averages(
  248. graph, trained_checkpoint_prefix, new_checkpoint_prefix)
  249. expected_variables = set(['conv2d/bias', 'conv2d/kernel'])
  250. variables_in_old_ckpt = self._get_variables_in_checkpoint(
  251. trained_checkpoint_prefix)
  252. self.assertIn('conv2d/bias/ExponentialMovingAverage',
  253. variables_in_old_ckpt)
  254. self.assertIn('conv2d/kernel/ExponentialMovingAverage',
  255. variables_in_old_ckpt)
  256. variables_in_new_ckpt = self._get_variables_in_checkpoint(
  257. new_checkpoint_prefix)
  258. self.assertTrue(expected_variables.issubset(variables_in_new_ckpt))
  259. self.assertNotIn('conv2d/bias/ExponentialMovingAverage',
  260. variables_in_new_ckpt)
  261. self.assertNotIn('conv2d/kernel/ExponentialMovingAverage',
  262. variables_in_new_ckpt)
  263. def test_export_graph_with_moving_averages(self):
  264. tmp_dir = self.get_temp_dir()
  265. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  266. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  267. use_moving_averages=True)
  268. output_directory = os.path.join(tmp_dir, 'output')
  269. with mock.patch.object(
  270. model_builder, 'build', autospec=True) as mock_builder:
  271. mock_builder.return_value = FakeModel()
  272. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  273. pipeline_config.eval_config.use_moving_averages = True
  274. exporter.export_inference_graph(
  275. input_type='image_tensor',
  276. pipeline_config=pipeline_config,
  277. trained_checkpoint_prefix=trained_checkpoint_prefix,
  278. output_directory=output_directory)
  279. self.assertTrue(os.path.exists(os.path.join(
  280. output_directory, 'saved_model', 'saved_model.pb')))
  281. expected_variables = set(['conv2d/bias', 'conv2d/kernel', 'global_step'])
  282. actual_variables = set(
  283. [var_name for var_name, _ in tf.train.list_variables(output_directory)])
  284. self.assertTrue(expected_variables.issubset(actual_variables))
  285. def test_export_model_with_quantization_nodes(self):
  286. tmp_dir = self.get_temp_dir()
  287. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  288. self._save_checkpoint_from_mock_model(
  289. trained_checkpoint_prefix,
  290. use_moving_averages=False,
  291. enable_quantization=True)
  292. output_directory = os.path.join(tmp_dir, 'output')
  293. inference_graph_path = os.path.join(output_directory,
  294. 'inference_graph.pbtxt')
  295. with mock.patch.object(
  296. model_builder, 'build', autospec=True) as mock_builder:
  297. mock_builder.return_value = FakeModel()
  298. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  299. text_format.Merge(
  300. """graph_rewriter {
  301. quantization {
  302. delay: 50000
  303. activation_bits: 8
  304. weight_bits: 8
  305. }
  306. }""", pipeline_config)
  307. exporter.export_inference_graph(
  308. input_type='image_tensor',
  309. pipeline_config=pipeline_config,
  310. trained_checkpoint_prefix=trained_checkpoint_prefix,
  311. output_directory=output_directory,
  312. write_inference_graph=True)
  313. self._load_inference_graph(inference_graph_path, is_binary=False)
  314. has_quant_nodes = False
  315. for v in tf.global_variables():
  316. if v.op.name.endswith('act_quant/min'):
  317. has_quant_nodes = True
  318. break
  319. self.assertTrue(has_quant_nodes)
  320. def test_export_model_with_all_output_nodes(self):
  321. tmp_dir = self.get_temp_dir()
  322. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  323. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  324. use_moving_averages=True)
  325. output_directory = os.path.join(tmp_dir, 'output')
  326. inference_graph_path = os.path.join(output_directory,
  327. 'frozen_inference_graph.pb')
  328. with mock.patch.object(
  329. model_builder, 'build', autospec=True) as mock_builder:
  330. mock_builder.return_value = FakeModel(
  331. add_detection_keypoints=True, add_detection_masks=True)
  332. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  333. exporter.export_inference_graph(
  334. input_type='image_tensor',
  335. pipeline_config=pipeline_config,
  336. trained_checkpoint_prefix=trained_checkpoint_prefix,
  337. output_directory=output_directory)
  338. inference_graph = self._load_inference_graph(inference_graph_path)
  339. with self.test_session(graph=inference_graph):
  340. inference_graph.get_tensor_by_name('image_tensor:0')
  341. inference_graph.get_tensor_by_name('detection_boxes:0')
  342. inference_graph.get_tensor_by_name('detection_scores:0')
  343. inference_graph.get_tensor_by_name('detection_classes:0')
  344. inference_graph.get_tensor_by_name('detection_keypoints:0')
  345. inference_graph.get_tensor_by_name('detection_masks:0')
  346. inference_graph.get_tensor_by_name('num_detections:0')
  347. def test_export_model_with_detection_only_nodes(self):
  348. tmp_dir = self.get_temp_dir()
  349. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  350. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  351. use_moving_averages=True)
  352. output_directory = os.path.join(tmp_dir, 'output')
  353. inference_graph_path = os.path.join(output_directory,
  354. 'frozen_inference_graph.pb')
  355. with mock.patch.object(
  356. model_builder, 'build', autospec=True) as mock_builder:
  357. mock_builder.return_value = FakeModel(add_detection_masks=False)
  358. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  359. exporter.export_inference_graph(
  360. input_type='image_tensor',
  361. pipeline_config=pipeline_config,
  362. trained_checkpoint_prefix=trained_checkpoint_prefix,
  363. output_directory=output_directory)
  364. inference_graph = self._load_inference_graph(inference_graph_path)
  365. with self.test_session(graph=inference_graph):
  366. inference_graph.get_tensor_by_name('image_tensor:0')
  367. inference_graph.get_tensor_by_name('detection_boxes:0')
  368. inference_graph.get_tensor_by_name('detection_scores:0')
  369. inference_graph.get_tensor_by_name('detection_classes:0')
  370. inference_graph.get_tensor_by_name('num_detections:0')
  371. with self.assertRaises(KeyError):
  372. inference_graph.get_tensor_by_name('detection_keypoints:0')
  373. inference_graph.get_tensor_by_name('detection_masks:0')
  374. def test_export_and_run_inference_with_image_tensor(self):
  375. tmp_dir = self.get_temp_dir()
  376. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  377. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  378. use_moving_averages=True)
  379. output_directory = os.path.join(tmp_dir, 'output')
  380. inference_graph_path = os.path.join(output_directory,
  381. 'frozen_inference_graph.pb')
  382. with mock.patch.object(
  383. model_builder, 'build', autospec=True) as mock_builder:
  384. mock_builder.return_value = FakeModel(
  385. add_detection_keypoints=True, add_detection_masks=True)
  386. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  387. pipeline_config.eval_config.use_moving_averages = False
  388. exporter.export_inference_graph(
  389. input_type='image_tensor',
  390. pipeline_config=pipeline_config,
  391. trained_checkpoint_prefix=trained_checkpoint_prefix,
  392. output_directory=output_directory)
  393. inference_graph = self._load_inference_graph(inference_graph_path)
  394. with self.test_session(graph=inference_graph) as sess:
  395. image_tensor = inference_graph.get_tensor_by_name('image_tensor:0')
  396. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  397. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  398. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  399. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  400. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  401. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  402. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  403. num_detections_np) = sess.run(
  404. [boxes, scores, classes, keypoints, masks, num_detections],
  405. feed_dict={image_tensor: np.ones((2, 4, 4, 3)).astype(np.uint8)})
  406. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  407. [0.5, 0.5, 0.8, 0.8]],
  408. [[0.5, 0.5, 1.0, 1.0],
  409. [0.0, 0.0, 0.0, 0.0]]])
  410. self.assertAllClose(scores_np, [[0.7, 0.6],
  411. [0.9, 0.0]])
  412. self.assertAllClose(classes_np, [[1, 2],
  413. [2, 1]])
  414. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  415. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  416. self.assertAllClose(num_detections_np, [2, 1])
  417. def _create_encoded_image_string(self, image_array_np, encoding_format):
  418. od_graph = tf.Graph()
  419. with od_graph.as_default():
  420. if encoding_format == 'jpg':
  421. encoded_string = tf.image.encode_jpeg(image_array_np)
  422. elif encoding_format == 'png':
  423. encoded_string = tf.image.encode_png(image_array_np)
  424. else:
  425. raise ValueError('Supports only the following formats: `jpg`, `png`')
  426. with self.test_session(graph=od_graph):
  427. return encoded_string.eval()
  428. def test_export_and_run_inference_with_encoded_image_string_tensor(self):
  429. tmp_dir = self.get_temp_dir()
  430. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  431. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  432. use_moving_averages=True)
  433. output_directory = os.path.join(tmp_dir, 'output')
  434. inference_graph_path = os.path.join(output_directory,
  435. 'frozen_inference_graph.pb')
  436. with mock.patch.object(
  437. model_builder, 'build', autospec=True) as mock_builder:
  438. mock_builder.return_value = FakeModel(
  439. add_detection_keypoints=True, add_detection_masks=True)
  440. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  441. pipeline_config.eval_config.use_moving_averages = False
  442. exporter.export_inference_graph(
  443. input_type='encoded_image_string_tensor',
  444. pipeline_config=pipeline_config,
  445. trained_checkpoint_prefix=trained_checkpoint_prefix,
  446. output_directory=output_directory)
  447. inference_graph = self._load_inference_graph(inference_graph_path)
  448. jpg_image_str = self._create_encoded_image_string(
  449. np.ones((4, 4, 3)).astype(np.uint8), 'jpg')
  450. png_image_str = self._create_encoded_image_string(
  451. np.ones((4, 4, 3)).astype(np.uint8), 'png')
  452. with self.test_session(graph=inference_graph) as sess:
  453. image_str_tensor = inference_graph.get_tensor_by_name(
  454. 'encoded_image_string_tensor:0')
  455. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  456. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  457. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  458. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  459. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  460. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  461. for image_str in [jpg_image_str, png_image_str]:
  462. image_str_batch_np = np.hstack([image_str]* 2)
  463. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  464. num_detections_np) = sess.run(
  465. [boxes, scores, classes, keypoints, masks, num_detections],
  466. feed_dict={image_str_tensor: image_str_batch_np})
  467. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  468. [0.5, 0.5, 0.8, 0.8]],
  469. [[0.5, 0.5, 1.0, 1.0],
  470. [0.0, 0.0, 0.0, 0.0]]])
  471. self.assertAllClose(scores_np, [[0.7, 0.6],
  472. [0.9, 0.0]])
  473. self.assertAllClose(classes_np, [[1, 2],
  474. [2, 1]])
  475. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  476. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  477. self.assertAllClose(num_detections_np, [2, 1])
  478. def test_raise_runtime_error_on_images_with_different_sizes(self):
  479. tmp_dir = self.get_temp_dir()
  480. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  481. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  482. use_moving_averages=True)
  483. output_directory = os.path.join(tmp_dir, 'output')
  484. inference_graph_path = os.path.join(output_directory,
  485. 'frozen_inference_graph.pb')
  486. with mock.patch.object(
  487. model_builder, 'build', autospec=True) as mock_builder:
  488. mock_builder.return_value = FakeModel(
  489. add_detection_keypoints=True, add_detection_masks=True)
  490. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  491. pipeline_config.eval_config.use_moving_averages = False
  492. exporter.export_inference_graph(
  493. input_type='encoded_image_string_tensor',
  494. pipeline_config=pipeline_config,
  495. trained_checkpoint_prefix=trained_checkpoint_prefix,
  496. output_directory=output_directory)
  497. inference_graph = self._load_inference_graph(inference_graph_path)
  498. large_image = self._create_encoded_image_string(
  499. np.ones((4, 4, 3)).astype(np.uint8), 'jpg')
  500. small_image = self._create_encoded_image_string(
  501. np.ones((2, 2, 3)).astype(np.uint8), 'jpg')
  502. image_str_batch_np = np.hstack([large_image, small_image])
  503. with self.test_session(graph=inference_graph) as sess:
  504. image_str_tensor = inference_graph.get_tensor_by_name(
  505. 'encoded_image_string_tensor:0')
  506. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  507. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  508. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  509. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  510. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  511. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  512. with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,
  513. 'TensorArray.*shape'):
  514. sess.run(
  515. [boxes, scores, classes, keypoints, masks, num_detections],
  516. feed_dict={image_str_tensor: image_str_batch_np})
  517. def test_export_and_run_inference_with_tf_example(self):
  518. tmp_dir = self.get_temp_dir()
  519. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  520. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  521. use_moving_averages=True)
  522. output_directory = os.path.join(tmp_dir, 'output')
  523. inference_graph_path = os.path.join(output_directory,
  524. 'frozen_inference_graph.pb')
  525. with mock.patch.object(
  526. model_builder, 'build', autospec=True) as mock_builder:
  527. mock_builder.return_value = FakeModel(
  528. add_detection_keypoints=True, add_detection_masks=True)
  529. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  530. pipeline_config.eval_config.use_moving_averages = False
  531. exporter.export_inference_graph(
  532. input_type='tf_example',
  533. pipeline_config=pipeline_config,
  534. trained_checkpoint_prefix=trained_checkpoint_prefix,
  535. output_directory=output_directory)
  536. inference_graph = self._load_inference_graph(inference_graph_path)
  537. tf_example_np = np.expand_dims(self._create_tf_example(
  538. np.ones((4, 4, 3)).astype(np.uint8)), axis=0)
  539. with self.test_session(graph=inference_graph) as sess:
  540. tf_example = inference_graph.get_tensor_by_name('tf_example:0')
  541. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  542. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  543. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  544. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  545. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  546. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  547. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  548. num_detections_np) = sess.run(
  549. [boxes, scores, classes, keypoints, masks, num_detections],
  550. feed_dict={tf_example: tf_example_np})
  551. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  552. [0.5, 0.5, 0.8, 0.8]],
  553. [[0.5, 0.5, 1.0, 1.0],
  554. [0.0, 0.0, 0.0, 0.0]]])
  555. self.assertAllClose(scores_np, [[0.7, 0.6],
  556. [0.9, 0.0]])
  557. self.assertAllClose(classes_np, [[1, 2],
  558. [2, 1]])
  559. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  560. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  561. self.assertAllClose(num_detections_np, [2, 1])
  562. def test_write_frozen_graph(self):
  563. tmp_dir = self.get_temp_dir()
  564. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  565. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  566. use_moving_averages=True)
  567. output_directory = os.path.join(tmp_dir, 'output')
  568. inference_graph_path = os.path.join(output_directory,
  569. 'frozen_inference_graph.pb')
  570. tf.gfile.MakeDirs(output_directory)
  571. with mock.patch.object(
  572. model_builder, 'build', autospec=True) as mock_builder:
  573. mock_builder.return_value = FakeModel(
  574. add_detection_keypoints=True, add_detection_masks=True)
  575. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  576. pipeline_config.eval_config.use_moving_averages = False
  577. detection_model = model_builder.build(pipeline_config.model,
  578. is_training=False)
  579. outputs, _ = exporter.build_detection_graph(
  580. input_type='tf_example',
  581. detection_model=detection_model,
  582. input_shape=None,
  583. output_collection_name='inference_op',
  584. graph_hook_fn=None)
  585. output_node_names = ','.join(outputs.keys())
  586. saver = tf.train.Saver()
  587. input_saver_def = saver.as_saver_def()
  588. exporter.freeze_graph_with_def_protos(
  589. input_graph_def=tf.get_default_graph().as_graph_def(),
  590. input_saver_def=input_saver_def,
  591. input_checkpoint=trained_checkpoint_prefix,
  592. output_node_names=output_node_names,
  593. restore_op_name='save/restore_all',
  594. filename_tensor_name='save/Const:0',
  595. output_graph=inference_graph_path,
  596. clear_devices=True,
  597. initializer_nodes='')
  598. inference_graph = self._load_inference_graph(inference_graph_path)
  599. tf_example_np = np.expand_dims(self._create_tf_example(
  600. np.ones((4, 4, 3)).astype(np.uint8)), axis=0)
  601. with self.test_session(graph=inference_graph) as sess:
  602. tf_example = inference_graph.get_tensor_by_name('tf_example:0')
  603. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  604. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  605. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  606. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  607. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  608. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  609. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  610. num_detections_np) = sess.run(
  611. [boxes, scores, classes, keypoints, masks, num_detections],
  612. feed_dict={tf_example: tf_example_np})
  613. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  614. [0.5, 0.5, 0.8, 0.8]],
  615. [[0.5, 0.5, 1.0, 1.0],
  616. [0.0, 0.0, 0.0, 0.0]]])
  617. self.assertAllClose(scores_np, [[0.7, 0.6],
  618. [0.9, 0.0]])
  619. self.assertAllClose(classes_np, [[1, 2],
  620. [2, 1]])
  621. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  622. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  623. self.assertAllClose(num_detections_np, [2, 1])
  624. def test_export_graph_saves_pipeline_file(self):
  625. tmp_dir = self.get_temp_dir()
  626. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  627. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  628. use_moving_averages=True)
  629. output_directory = os.path.join(tmp_dir, 'output')
  630. with mock.patch.object(
  631. model_builder, 'build', autospec=True) as mock_builder:
  632. mock_builder.return_value = FakeModel()
  633. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  634. exporter.export_inference_graph(
  635. input_type='image_tensor',
  636. pipeline_config=pipeline_config,
  637. trained_checkpoint_prefix=trained_checkpoint_prefix,
  638. output_directory=output_directory)
  639. expected_pipeline_path = os.path.join(
  640. output_directory, 'pipeline.config')
  641. self.assertTrue(os.path.exists(expected_pipeline_path))
  642. written_pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  643. with tf.gfile.GFile(expected_pipeline_path, 'r') as f:
  644. proto_str = f.read()
  645. text_format.Merge(proto_str, written_pipeline_config)
  646. self.assertProtoEquals(pipeline_config, written_pipeline_config)
  647. def test_export_saved_model_and_run_inference(self):
  648. tmp_dir = self.get_temp_dir()
  649. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  650. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  651. use_moving_averages=False)
  652. output_directory = os.path.join(tmp_dir, 'output')
  653. saved_model_path = os.path.join(output_directory, 'saved_model')
  654. with mock.patch.object(
  655. model_builder, 'build', autospec=True) as mock_builder:
  656. mock_builder.return_value = FakeModel(
  657. add_detection_keypoints=True, add_detection_masks=True)
  658. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  659. pipeline_config.eval_config.use_moving_averages = False
  660. exporter.export_inference_graph(
  661. input_type='tf_example',
  662. pipeline_config=pipeline_config,
  663. trained_checkpoint_prefix=trained_checkpoint_prefix,
  664. output_directory=output_directory)
  665. tf_example_np = np.hstack([self._create_tf_example(
  666. np.ones((4, 4, 3)).astype(np.uint8))] * 2)
  667. with tf.Graph().as_default() as od_graph:
  668. with self.test_session(graph=od_graph) as sess:
  669. meta_graph = tf.saved_model.loader.load(
  670. sess, [tf.saved_model.tag_constants.SERVING], saved_model_path)
  671. signature = meta_graph.signature_def['serving_default']
  672. input_tensor_name = signature.inputs['inputs'].name
  673. tf_example = od_graph.get_tensor_by_name(input_tensor_name)
  674. boxes = od_graph.get_tensor_by_name(
  675. signature.outputs['detection_boxes'].name)
  676. scores = od_graph.get_tensor_by_name(
  677. signature.outputs['detection_scores'].name)
  678. classes = od_graph.get_tensor_by_name(
  679. signature.outputs['detection_classes'].name)
  680. keypoints = od_graph.get_tensor_by_name(
  681. signature.outputs['detection_keypoints'].name)
  682. masks = od_graph.get_tensor_by_name(
  683. signature.outputs['detection_masks'].name)
  684. num_detections = od_graph.get_tensor_by_name(
  685. signature.outputs['num_detections'].name)
  686. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  687. num_detections_np) = sess.run(
  688. [boxes, scores, classes, keypoints, masks, num_detections],
  689. feed_dict={tf_example: tf_example_np})
  690. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  691. [0.5, 0.5, 0.8, 0.8]],
  692. [[0.5, 0.5, 1.0, 1.0],
  693. [0.0, 0.0, 0.0, 0.0]]])
  694. self.assertAllClose(scores_np, [[0.7, 0.6],
  695. [0.9, 0.0]])
  696. self.assertAllClose(classes_np, [[1, 2],
  697. [2, 1]])
  698. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  699. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  700. self.assertAllClose(num_detections_np, [2, 1])
  701. def test_write_saved_model(self):
  702. tmp_dir = self.get_temp_dir()
  703. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  704. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  705. use_moving_averages=False)
  706. output_directory = os.path.join(tmp_dir, 'output')
  707. saved_model_path = os.path.join(output_directory, 'saved_model')
  708. tf.gfile.MakeDirs(output_directory)
  709. with mock.patch.object(
  710. model_builder, 'build', autospec=True) as mock_builder:
  711. mock_builder.return_value = FakeModel(
  712. add_detection_keypoints=True, add_detection_masks=True)
  713. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  714. pipeline_config.eval_config.use_moving_averages = False
  715. detection_model = model_builder.build(pipeline_config.model,
  716. is_training=False)
  717. outputs, placeholder_tensor = exporter.build_detection_graph(
  718. input_type='tf_example',
  719. detection_model=detection_model,
  720. input_shape=None,
  721. output_collection_name='inference_op',
  722. graph_hook_fn=None)
  723. output_node_names = ','.join(outputs.keys())
  724. saver = tf.train.Saver()
  725. input_saver_def = saver.as_saver_def()
  726. frozen_graph_def = exporter.freeze_graph_with_def_protos(
  727. input_graph_def=tf.get_default_graph().as_graph_def(),
  728. input_saver_def=input_saver_def,
  729. input_checkpoint=trained_checkpoint_prefix,
  730. output_node_names=output_node_names,
  731. restore_op_name='save/restore_all',
  732. filename_tensor_name='save/Const:0',
  733. output_graph='',
  734. clear_devices=True,
  735. initializer_nodes='')
  736. exporter.write_saved_model(
  737. saved_model_path=saved_model_path,
  738. frozen_graph_def=frozen_graph_def,
  739. inputs=placeholder_tensor,
  740. outputs=outputs)
  741. tf_example_np = np.hstack([self._create_tf_example(
  742. np.ones((4, 4, 3)).astype(np.uint8))] * 2)
  743. with tf.Graph().as_default() as od_graph:
  744. with self.test_session(graph=od_graph) as sess:
  745. meta_graph = tf.saved_model.loader.load(
  746. sess, [tf.saved_model.tag_constants.SERVING], saved_model_path)
  747. signature = meta_graph.signature_def['serving_default']
  748. input_tensor_name = signature.inputs['inputs'].name
  749. tf_example = od_graph.get_tensor_by_name(input_tensor_name)
  750. boxes = od_graph.get_tensor_by_name(
  751. signature.outputs['detection_boxes'].name)
  752. scores = od_graph.get_tensor_by_name(
  753. signature.outputs['detection_scores'].name)
  754. classes = od_graph.get_tensor_by_name(
  755. signature.outputs['detection_classes'].name)
  756. keypoints = od_graph.get_tensor_by_name(
  757. signature.outputs['detection_keypoints'].name)
  758. masks = od_graph.get_tensor_by_name(
  759. signature.outputs['detection_masks'].name)
  760. num_detections = od_graph.get_tensor_by_name(
  761. signature.outputs['num_detections'].name)
  762. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  763. num_detections_np) = sess.run(
  764. [boxes, scores, classes, keypoints, masks, num_detections],
  765. feed_dict={tf_example: tf_example_np})
  766. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  767. [0.5, 0.5, 0.8, 0.8]],
  768. [[0.5, 0.5, 1.0, 1.0],
  769. [0.0, 0.0, 0.0, 0.0]]])
  770. self.assertAllClose(scores_np, [[0.7, 0.6],
  771. [0.9, 0.0]])
  772. self.assertAllClose(classes_np, [[1, 2],
  773. [2, 1]])
  774. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  775. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  776. self.assertAllClose(num_detections_np, [2, 1])
  777. def test_export_checkpoint_and_run_inference(self):
  778. tmp_dir = self.get_temp_dir()
  779. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  780. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  781. use_moving_averages=False)
  782. output_directory = os.path.join(tmp_dir, 'output')
  783. model_path = os.path.join(output_directory, 'model.ckpt')
  784. meta_graph_path = model_path + '.meta'
  785. with mock.patch.object(
  786. model_builder, 'build', autospec=True) as mock_builder:
  787. mock_builder.return_value = FakeModel(
  788. add_detection_keypoints=True, add_detection_masks=True)
  789. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  790. pipeline_config.eval_config.use_moving_averages = False
  791. exporter.export_inference_graph(
  792. input_type='tf_example',
  793. pipeline_config=pipeline_config,
  794. trained_checkpoint_prefix=trained_checkpoint_prefix,
  795. output_directory=output_directory)
  796. tf_example_np = np.hstack([self._create_tf_example(
  797. np.ones((4, 4, 3)).astype(np.uint8))] * 2)
  798. with tf.Graph().as_default() as od_graph:
  799. with self.test_session(graph=od_graph) as sess:
  800. new_saver = tf.train.import_meta_graph(meta_graph_path)
  801. new_saver.restore(sess, model_path)
  802. tf_example = od_graph.get_tensor_by_name('tf_example:0')
  803. boxes = od_graph.get_tensor_by_name('detection_boxes:0')
  804. scores = od_graph.get_tensor_by_name('detection_scores:0')
  805. classes = od_graph.get_tensor_by_name('detection_classes:0')
  806. keypoints = od_graph.get_tensor_by_name('detection_keypoints:0')
  807. masks = od_graph.get_tensor_by_name('detection_masks:0')
  808. num_detections = od_graph.get_tensor_by_name('num_detections:0')
  809. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  810. num_detections_np) = sess.run(
  811. [boxes, scores, classes, keypoints, masks, num_detections],
  812. feed_dict={tf_example: tf_example_np})
  813. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  814. [0.5, 0.5, 0.8, 0.8]],
  815. [[0.5, 0.5, 1.0, 1.0],
  816. [0.0, 0.0, 0.0, 0.0]]])
  817. self.assertAllClose(scores_np, [[0.7, 0.6],
  818. [0.9, 0.0]])
  819. self.assertAllClose(classes_np, [[1, 2],
  820. [2, 1]])
  821. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  822. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  823. self.assertAllClose(num_detections_np, [2, 1])
  824. def test_write_graph_and_checkpoint(self):
  825. tmp_dir = self.get_temp_dir()
  826. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  827. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  828. use_moving_averages=False)
  829. output_directory = os.path.join(tmp_dir, 'output')
  830. model_path = os.path.join(output_directory, 'model.ckpt')
  831. meta_graph_path = model_path + '.meta'
  832. tf.gfile.MakeDirs(output_directory)
  833. with mock.patch.object(
  834. model_builder, 'build', autospec=True) as mock_builder:
  835. mock_builder.return_value = FakeModel(
  836. add_detection_keypoints=True, add_detection_masks=True)
  837. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  838. pipeline_config.eval_config.use_moving_averages = False
  839. detection_model = model_builder.build(pipeline_config.model,
  840. is_training=False)
  841. exporter.build_detection_graph(
  842. input_type='tf_example',
  843. detection_model=detection_model,
  844. input_shape=None,
  845. output_collection_name='inference_op',
  846. graph_hook_fn=None)
  847. saver = tf.train.Saver()
  848. input_saver_def = saver.as_saver_def()
  849. exporter.write_graph_and_checkpoint(
  850. inference_graph_def=tf.get_default_graph().as_graph_def(),
  851. model_path=model_path,
  852. input_saver_def=input_saver_def,
  853. trained_checkpoint_prefix=trained_checkpoint_prefix)
  854. tf_example_np = np.hstack([self._create_tf_example(
  855. np.ones((4, 4, 3)).astype(np.uint8))] * 2)
  856. with tf.Graph().as_default() as od_graph:
  857. with self.test_session(graph=od_graph) as sess:
  858. new_saver = tf.train.import_meta_graph(meta_graph_path)
  859. new_saver.restore(sess, model_path)
  860. tf_example = od_graph.get_tensor_by_name('tf_example:0')
  861. boxes = od_graph.get_tensor_by_name('detection_boxes:0')
  862. scores = od_graph.get_tensor_by_name('detection_scores:0')
  863. raw_boxes = od_graph.get_tensor_by_name('raw_detection_boxes:0')
  864. raw_scores = od_graph.get_tensor_by_name('raw_detection_scores:0')
  865. classes = od_graph.get_tensor_by_name('detection_classes:0')
  866. keypoints = od_graph.get_tensor_by_name('detection_keypoints:0')
  867. masks = od_graph.get_tensor_by_name('detection_masks:0')
  868. num_detections = od_graph.get_tensor_by_name('num_detections:0')
  869. (boxes_np, scores_np, raw_boxes_np, raw_scores_np, classes_np,
  870. keypoints_np, masks_np, num_detections_np) = sess.run(
  871. [boxes, scores, raw_boxes, raw_scores, classes, keypoints, masks,
  872. num_detections],
  873. feed_dict={tf_example: tf_example_np})
  874. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  875. [0.5, 0.5, 0.8, 0.8]],
  876. [[0.5, 0.5, 1.0, 1.0],
  877. [0.0, 0.0, 0.0, 0.0]]])
  878. self.assertAllClose(scores_np, [[0.7, 0.6],
  879. [0.9, 0.0]])
  880. self.assertAllClose(raw_boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  881. [0.5, 0.5, 0.8, 0.8]],
  882. [[0.5, 0.5, 1.0, 1.0],
  883. [0.0, 0.5, 0.0, 0.5]]])
  884. self.assertAllClose(raw_scores_np, [[0.7, 0.6],
  885. [0.9, 0.5]])
  886. self.assertAllClose(classes_np, [[1, 2],
  887. [2, 1]])
  888. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  889. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  890. self.assertAllClose(num_detections_np, [2, 1])
  891. def test_rewrite_nn_resize_op(self):
  892. g = tf.Graph()
  893. with g.as_default():
  894. x = array_ops.placeholder(dtypes.float32, shape=(8, 10, 10, 8))
  895. y = array_ops.placeholder(dtypes.float32, shape=(8, 20, 20, 8))
  896. s = ops.nearest_neighbor_upsampling(x, 2)
  897. t = s + y
  898. exporter.rewrite_nn_resize_op()
  899. resize_op_found = False
  900. for op in g.get_operations():
  901. if op.type == 'ResizeNearestNeighbor':
  902. resize_op_found = True
  903. self.assertEqual(op.inputs[0], x)
  904. self.assertEqual(op.outputs[0].consumers()[0], t.op)
  905. break
  906. self.assertTrue(resize_op_found)
  907. def test_rewrite_nn_resize_op_quantized(self):
  908. g = tf.Graph()
  909. with g.as_default():
  910. x = array_ops.placeholder(dtypes.float32, shape=(8, 10, 10, 8))
  911. x_conv = tf.contrib.slim.conv2d(x, 8, 1)
  912. y = array_ops.placeholder(dtypes.float32, shape=(8, 20, 20, 8))
  913. s = ops.nearest_neighbor_upsampling(x_conv, 2)
  914. t = s + y
  915. graph_rewriter_config = graph_rewriter_pb2.GraphRewriter()
  916. graph_rewriter_config.quantization.delay = 500000
  917. graph_rewriter_fn = graph_rewriter_builder.build(
  918. graph_rewriter_config, is_training=False)
  919. graph_rewriter_fn()
  920. exporter.rewrite_nn_resize_op(is_quantized=True)
  921. resize_op_found = False
  922. for op in g.get_operations():
  923. if op.type == 'ResizeNearestNeighbor':
  924. resize_op_found = True
  925. self.assertEqual(op.inputs[0].op.type, 'FakeQuantWithMinMaxVars')
  926. self.assertEqual(op.outputs[0].consumers()[0], t.op)
  927. break
  928. self.assertTrue(resize_op_found)
  929. if __name__ == '__main__':
  930. tf.test.main()