exporter_test.py 21.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Tests for object_detection.export_inference_graph."""
import os
import numpy as np
19
import six
20
21
22
23
24
25
import tensorflow as tf
from object_detection import exporter
from object_detection.builders import model_builder
from object_detection.core import model
from object_detection.protos import pipeline_pb2

26
27
28
29
30
if six.PY2:
  import mock  # pylint: disable=g-import-not-at-top
else:
  from unittest import mock  # pylint: disable=g-import-not-at-top

31
32
33

class FakeModel(model.DetectionModel):

34
35
36
  def __init__(self, add_detection_masks=False):
    self._add_detection_masks = add_detection_masks

37
  def preprocess(self, inputs):
38
    return tf.identity(inputs)
39
40

  def predict(self, preprocessed_inputs):
41
    return {'image': tf.layers.conv2d(preprocessed_inputs, 3, 1)}
42
43
44

  def postprocess(self, prediction_dict):
    with tf.control_dependencies(prediction_dict.values()):
45
      postprocessed_tensors = {
46
47
48
49
50
51
          'detection_boxes': tf.constant([[0.0, 0.0, 0.5, 0.5],
                                          [0.5, 0.5, 0.8, 0.8]], tf.float32),
          'detection_scores': tf.constant([[0.7, 0.6]], tf.float32),
          'detection_classes': tf.constant([[0, 1]], tf.float32),
          'num_detections': tf.constant([2], tf.float32)
      }
52
53
54
55
      if self._add_detection_masks:
        postprocessed_tensors['detection_masks'] = tf.constant(
            np.arange(32).reshape([2, 4, 4]), tf.float32)
    return postprocessed_tensors
56

57
  def restore_map(self, checkpoint_path, from_detection_checkpoint):
58
59
60
61
62
63
64
65
66
67
68
69
    pass

  def loss(self, prediction_dict):
    pass


class ExportInferenceGraphTest(tf.test.TestCase):

  def _save_checkpoint_from_mock_model(self, checkpoint_path,
                                       use_moving_averages):
    g = tf.Graph()
    with g.as_default():
70
71
72
73
74
      mock_model = FakeModel()
      preprocessed_inputs = mock_model.preprocess(
          tf.ones([1, 3, 4, 3], tf.float32))
      predictions = mock_model.predict(preprocessed_inputs)
      mock_model.postprocess(predictions)
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
      if use_moving_averages:
        tf.train.ExponentialMovingAverage(0.0).apply()
      saver = tf.train.Saver()
      init = tf.global_variables_initializer()
      with self.test_session() as sess:
        sess.run(init)
        saver.save(sess, checkpoint_path)

  def _load_inference_graph(self, inference_graph_path):
    od_graph = tf.Graph()
    with od_graph.as_default():
      od_graph_def = tf.GraphDef()
      with tf.gfile.GFile(inference_graph_path) as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')
    return od_graph

  def _create_tf_example(self, image_array):
    with self.test_session():
      encoded_image = tf.image.encode_jpeg(tf.constant(image_array)).eval()
    def _bytes_feature(value):
      return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
    example = tf.train.Example(features=tf.train.Features(feature={
        'image/encoded': _bytes_feature(encoded_image),
        'image/format': _bytes_feature('jpg'),
        'image/source_id': _bytes_feature('image_id')
    })).SerializeToString()
    return example

  def test_export_graph_with_image_tensor_input(self):
106
107
108
109
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
                                          use_moving_averages=False)
110
111
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
112
      mock_builder.return_value = FakeModel()
113
      output_directory = os.path.join(tmp_dir, 'output')
114
115
116
117
118
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = False
      exporter.export_inference_graph(
          input_type='image_tensor',
          pipeline_config=pipeline_config,
119
120
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
121
122

  def test_export_graph_with_tf_example_input(self):
123
124
125
126
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
                                          use_moving_averages=False)
127
128
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
129
      mock_builder.return_value = FakeModel()
130
      output_directory = os.path.join(tmp_dir, 'output')
131
132
133
134
135
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = False
      exporter.export_inference_graph(
          input_type='tf_example',
          pipeline_config=pipeline_config,
136
137
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
138

139
  def test_export_graph_with_encoded_image_string_input(self):
140
141
142
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
143
144
145
                                          use_moving_averages=False)
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
146
      mock_builder.return_value = FakeModel()
147
      output_directory = os.path.join(tmp_dir, 'output')
148
149
150
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = False
      exporter.export_inference_graph(
151
          input_type='encoded_image_string_tensor',
152
          pipeline_config=pipeline_config,
153
154
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
155

156
157
158
159
  def test_export_graph_with_moving_averages(self):
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
160
                                          use_moving_averages=True)
161
    output_directory = os.path.join(tmp_dir, 'output')
162
163
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
164
      mock_builder.return_value = FakeModel()
165
166
167
168
169
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = True
      exporter.export_inference_graph(
          input_type='image_tensor',
          pipeline_config=pipeline_config,
170
171
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
172

173
  def test_export_model_with_all_output_nodes(self):
174
175
176
177
178
179
180
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
                                          use_moving_averages=True)
    output_directory = os.path.join(tmp_dir, 'output')
    inference_graph_path = os.path.join(output_directory,
                                        'frozen_inference_graph.pb')
181
182
183
184
185
186
187
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
      mock_builder.return_value = FakeModel(add_detection_masks=True)
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      exporter.export_inference_graph(
          input_type='image_tensor',
          pipeline_config=pipeline_config,
188
189
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
190
191
192
193
194
195
196
197
198
199
    inference_graph = self._load_inference_graph(inference_graph_path)
    with self.test_session(graph=inference_graph):
      inference_graph.get_tensor_by_name('image_tensor:0')
      inference_graph.get_tensor_by_name('detection_boxes:0')
      inference_graph.get_tensor_by_name('detection_scores:0')
      inference_graph.get_tensor_by_name('detection_classes:0')
      inference_graph.get_tensor_by_name('detection_masks:0')
      inference_graph.get_tensor_by_name('num_detections:0')

  def test_export_model_with_detection_only_nodes(self):
200
201
202
203
204
205
206
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
                                          use_moving_averages=True)
    output_directory = os.path.join(tmp_dir, 'output')
    inference_graph_path = os.path.join(output_directory,
                                        'frozen_inference_graph.pb')
207
208
209
210
211
212
213
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
      mock_builder.return_value = FakeModel(add_detection_masks=False)
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      exporter.export_inference_graph(
          input_type='image_tensor',
          pipeline_config=pipeline_config,
214
215
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
216
217
218
219
220
221
222
223
224
225
    inference_graph = self._load_inference_graph(inference_graph_path)
    with self.test_session(graph=inference_graph):
      inference_graph.get_tensor_by_name('image_tensor:0')
      inference_graph.get_tensor_by_name('detection_boxes:0')
      inference_graph.get_tensor_by_name('detection_scores:0')
      inference_graph.get_tensor_by_name('detection_classes:0')
      inference_graph.get_tensor_by_name('num_detections:0')
      with self.assertRaises(KeyError):
        inference_graph.get_tensor_by_name('detection_masks:0')

226
  def test_export_and_run_inference_with_image_tensor(self):
227
228
229
230
231
232
233
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
                                          use_moving_averages=True)
    output_directory = os.path.join(tmp_dir, 'output')
    inference_graph_path = os.path.join(output_directory,
                                        'frozen_inference_graph.pb')
234
235
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
236
      mock_builder.return_value = FakeModel(add_detection_masks=True)
237
238
239
240
241
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = False
      exporter.export_inference_graph(
          input_type='image_tensor',
          pipeline_config=pipeline_config,
242
243
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
244
245
246
247
248
249
250

    inference_graph = self._load_inference_graph(inference_graph_path)
    with self.test_session(graph=inference_graph) as sess:
      image_tensor = inference_graph.get_tensor_by_name('image_tensor:0')
      boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
      scores = inference_graph.get_tensor_by_name('detection_scores:0')
      classes = inference_graph.get_tensor_by_name('detection_classes:0')
251
      masks = inference_graph.get_tensor_by_name('detection_masks:0')
252
      num_detections = inference_graph.get_tensor_by_name('num_detections:0')
253
254
      (boxes, scores, classes, masks, num_detections) = sess.run(
          [boxes, scores, classes, masks, num_detections],
255
256
257
258
259
          feed_dict={image_tensor: np.ones((1, 4, 4, 3)).astype(np.uint8)})
      self.assertAllClose(boxes, [[0.0, 0.0, 0.5, 0.5],
                                  [0.5, 0.5, 0.8, 0.8]])
      self.assertAllClose(scores, [[0.7, 0.6]])
      self.assertAllClose(classes, [[1, 2]])
260
      self.assertAllClose(masks, np.arange(32).reshape([2, 4, 4]))
261
262
      self.assertAllClose(num_detections, [2])

263
264
265
266
267
268
269
270
271
272
273
274
275
  def _create_encoded_image_string(self, image_array_np, encoding_format):
    od_graph = tf.Graph()
    with od_graph.as_default():
      if encoding_format == 'jpg':
        encoded_string = tf.image.encode_jpeg(image_array_np)
      elif encoding_format == 'png':
        encoded_string = tf.image.encode_png(image_array_np)
      else:
        raise ValueError('Supports only the following formats: `jpg`, `png`')
    with self.test_session(graph=od_graph):
      return encoded_string.eval()

  def test_export_and_run_inference_with_encoded_image_string_tensor(self):
276
277
278
279
280
281
282
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
                                          use_moving_averages=True)
    output_directory = os.path.join(tmp_dir, 'output')
    inference_graph_path = os.path.join(output_directory,
                                        'frozen_inference_graph.pb')
283
284
285
286
287
288
289
290
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
      mock_builder.return_value = FakeModel(add_detection_masks=True)
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = False
      exporter.export_inference_graph(
          input_type='encoded_image_string_tensor',
          pipeline_config=pipeline_config,
291
292
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318

    inference_graph = self._load_inference_graph(inference_graph_path)
    jpg_image_str = self._create_encoded_image_string(
        np.ones((4, 4, 3)).astype(np.uint8), 'jpg')
    png_image_str = self._create_encoded_image_string(
        np.ones((4, 4, 3)).astype(np.uint8), 'png')
    with self.test_session(graph=inference_graph) as sess:
      image_str_tensor = inference_graph.get_tensor_by_name(
          'encoded_image_string_tensor:0')
      boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
      scores = inference_graph.get_tensor_by_name('detection_scores:0')
      classes = inference_graph.get_tensor_by_name('detection_classes:0')
      masks = inference_graph.get_tensor_by_name('detection_masks:0')
      num_detections = inference_graph.get_tensor_by_name('num_detections:0')
      for image_str in [jpg_image_str, png_image_str]:
        (boxes_np, scores_np, classes_np, masks_np,
         num_detections_np) = sess.run(
             [boxes, scores, classes, masks, num_detections],
             feed_dict={image_str_tensor: image_str})
        self.assertAllClose(boxes_np, [[0.0, 0.0, 0.5, 0.5],
                                       [0.5, 0.5, 0.8, 0.8]])
        self.assertAllClose(scores_np, [[0.7, 0.6]])
        self.assertAllClose(classes_np, [[1, 2]])
        self.assertAllClose(masks_np, np.arange(32).reshape([2, 4, 4]))
        self.assertAllClose(num_detections_np, [2])

319
  def test_export_and_run_inference_with_tf_example(self):
320
321
322
323
324
325
326
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
                                          use_moving_averages=True)
    output_directory = os.path.join(tmp_dir, 'output')
    inference_graph_path = os.path.join(output_directory,
                                        'frozen_inference_graph.pb')
327
328
    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
329
      mock_builder.return_value = FakeModel(add_detection_masks=True)
330
331
332
333
334
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = False
      exporter.export_inference_graph(
          input_type='tf_example',
          pipeline_config=pipeline_config,
335
336
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
337
338
339
340
341
342
343

    inference_graph = self._load_inference_graph(inference_graph_path)
    with self.test_session(graph=inference_graph) as sess:
      tf_example = inference_graph.get_tensor_by_name('tf_example:0')
      boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
      scores = inference_graph.get_tensor_by_name('detection_scores:0')
      classes = inference_graph.get_tensor_by_name('detection_classes:0')
344
      masks = inference_graph.get_tensor_by_name('detection_masks:0')
345
      num_detections = inference_graph.get_tensor_by_name('num_detections:0')
346
347
      (boxes, scores, classes, masks, num_detections) = sess.run(
          [boxes, scores, classes, masks, num_detections],
348
349
350
351
352
353
          feed_dict={tf_example: self._create_tf_example(
              np.ones((4, 4, 3)).astype(np.uint8))})
      self.assertAllClose(boxes, [[0.0, 0.0, 0.5, 0.5],
                                  [0.5, 0.5, 0.8, 0.8]])
      self.assertAllClose(scores, [[0.7, 0.6]])
      self.assertAllClose(classes, [[1, 2]])
354
      self.assertAllClose(masks, np.arange(32).reshape([2, 4, 4]))
355
356
      self.assertAllClose(num_detections, [2])

357
  def test_export_saved_model_and_run_inference(self):
358
359
360
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
361
                                          use_moving_averages=False)
362
363
    output_directory = os.path.join(tmp_dir, 'output')
    saved_model_path = os.path.join(output_directory, 'saved_model')
364
365
366
367
368
369
370
371
372

    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
      mock_builder.return_value = FakeModel(add_detection_masks=True)
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = False
      exporter.export_inference_graph(
          input_type='tf_example',
          pipeline_config=pipeline_config,
373
374
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)
375
376
377
378

    with tf.Graph().as_default() as od_graph:
      with self.test_session(graph=od_graph) as sess:
        tf.saved_model.loader.load(
379
380
381
382
383
384
385
            sess, [tf.saved_model.tag_constants.SERVING], saved_model_path)
        tf_example = od_graph.get_tensor_by_name('tf_example:0')
        boxes = od_graph.get_tensor_by_name('detection_boxes:0')
        scores = od_graph.get_tensor_by_name('detection_scores:0')
        classes = od_graph.get_tensor_by_name('detection_classes:0')
        masks = od_graph.get_tensor_by_name('detection_masks:0')
        num_detections = od_graph.get_tensor_by_name('num_detections:0')
386
387
388
389
390
391
392
393
394
395
        (boxes, scores, classes, masks, num_detections) = sess.run(
            [boxes, scores, classes, masks, num_detections],
            feed_dict={tf_example: self._create_tf_example(
                np.ones((4, 4, 3)).astype(np.uint8))})
        self.assertAllClose(boxes, [[0.0, 0.0, 0.5, 0.5],
                                    [0.5, 0.5, 0.8, 0.8]])
        self.assertAllClose(scores, [[0.7, 0.6]])
        self.assertAllClose(classes, [[1, 2]])
        self.assertAllClose(masks, np.arange(32).reshape([2, 4, 4]))
        self.assertAllClose(num_detections, [2])
396

397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
  def test_export_checkpoint_and_run_inference(self):
    tmp_dir = self.get_temp_dir()
    trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
    self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
                                          use_moving_averages=False)
    output_directory = os.path.join(tmp_dir, 'output')
    model_path = os.path.join(output_directory, 'model.ckpt')
    meta_graph_path = model_path + '.meta'

    with mock.patch.object(
        model_builder, 'build', autospec=True) as mock_builder:
      mock_builder.return_value = FakeModel(add_detection_masks=True)
      pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
      pipeline_config.eval_config.use_moving_averages = False
      exporter.export_inference_graph(
          input_type='tf_example',
          pipeline_config=pipeline_config,
          trained_checkpoint_prefix=trained_checkpoint_prefix,
          output_directory=output_directory)

    with tf.Graph().as_default() as od_graph:
      with self.test_session(graph=od_graph) as sess:
        new_saver = tf.train.import_meta_graph(meta_graph_path)
        new_saver.restore(sess, model_path)

        tf_example = od_graph.get_tensor_by_name('tf_example:0')
        boxes = od_graph.get_tensor_by_name('detection_boxes:0')
        scores = od_graph.get_tensor_by_name('detection_scores:0')
        classes = od_graph.get_tensor_by_name('detection_classes:0')
        masks = od_graph.get_tensor_by_name('detection_masks:0')
        num_detections = od_graph.get_tensor_by_name('num_detections:0')
        (boxes, scores, classes, masks, num_detections) = sess.run(
            [boxes, scores, classes, masks, num_detections],
            feed_dict={tf_example: self._create_tf_example(
                np.ones((4, 4, 3)).astype(np.uint8))})
        self.assertAllClose(boxes, [[0.0, 0.0, 0.5, 0.5],
                                    [0.5, 0.5, 0.8, 0.8]])
        self.assertAllClose(scores, [[0.7, 0.6]])
        self.assertAllClose(classes, [[1, 2]])
        self.assertAllClose(masks, np.arange(32).reshape([2, 4, 4]))
        self.assertAllClose(num_detections, [2])


440
441
if __name__ == '__main__':
  tf.test.main()