"official/vision/dataloaders/utils.py" did not exist on "fd67924ca171d7f5a51c12188a6f52e2d0baa994"
detection.py 5.23 KB
Newer Older
Abdullah Rashwan's avatar
Abdullah Rashwan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Lint as: python3
# Copyright 2020 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.
# ==============================================================================
"""Detection input and model functions for serving/inference."""

import tensorflow as tf

from official.vision.beta import configs
from official.vision.beta.modeling import factory
from official.vision.beta.ops import anchor
from official.vision.beta.ops import preprocess_ops
from official.vision.beta.serving import export_base


MEAN_RGB = (0.485 * 255, 0.456 * 255, 0.406 * 255)
STDDEV_RGB = (0.229 * 255, 0.224 * 255, 0.225 * 255)


class DetectionModule(export_base.ExportModule):
  """Detection Module."""

Hongkun Yu's avatar
Hongkun Yu committed
34
  def _build_model(self):
Abdullah Rashwan's avatar
Abdullah Rashwan committed
35
36
37

    if self._batch_size is None:
      ValueError("batch_size can't be None for detection models")
Hongkun Yu's avatar
Hongkun Yu committed
38
    if not self.params.task.model.detection_generator.use_batched_nms:
Abdullah Rashwan's avatar
Abdullah Rashwan committed
39
40
41
42
      ValueError('Only batched_nms is supported.')
    input_specs = tf.keras.layers.InputSpec(shape=[self._batch_size] +
                                            self._input_image_size + [3])

Hongkun Yu's avatar
Hongkun Yu committed
43
44
45
46
47
48
    if isinstance(self.params.task.model, configs.maskrcnn.MaskRCNN):
      model = factory.build_maskrcnn(
          input_specs=input_specs, model_config=self.params.task.model)
    elif isinstance(self.params.task.model, configs.retinanet.RetinaNet):
      model = factory.build_retinanet(
          input_specs=input_specs, model_config=self.params.task.model)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
49
50
    else:
      raise ValueError('Detection module not implemented for {} model.'.format(
Hongkun Yu's avatar
Hongkun Yu committed
51
          type(self.params.task.model)))
Abdullah Rashwan's avatar
Abdullah Rashwan committed
52

Hongkun Yu's avatar
Hongkun Yu committed
53
    return model
Abdullah Rashwan's avatar
Abdullah Rashwan committed
54
55

  def _build_inputs(self, image):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
56
    """Builds detection model inputs for serving."""
Hongkun Yu's avatar
Hongkun Yu committed
57
    model_params = self.params.task.model
Abdullah Rashwan's avatar
Abdullah Rashwan committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    # Normalizes image with mean and std pixel values.
    image = preprocess_ops.normalize_image(image,
                                           offset=MEAN_RGB,
                                           scale=STDDEV_RGB)

    image, image_info = preprocess_ops.resize_and_crop_image(
        image,
        self._input_image_size,
        padded_size=preprocess_ops.compute_padded_size(
            self._input_image_size, 2**model_params.max_level),
        aug_scale_min=1.0,
        aug_scale_max=1.0)

    input_anchor = anchor.build_anchor_generator(
        min_level=model_params.min_level,
        max_level=model_params.max_level,
        num_scales=model_params.anchor.num_scales,
        aspect_ratios=model_params.anchor.aspect_ratios,
        anchor_size=model_params.anchor.anchor_size)
    anchor_boxes = input_anchor(image_size=(self._input_image_size[0],
                                            self._input_image_size[1]))

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
80
    return image, anchor_boxes, image_info
Abdullah Rashwan's avatar
Abdullah Rashwan committed
81

Hongkun Yu's avatar
Hongkun Yu committed
82
  def serve(self, images: tf.Tensor):
Abdullah Rashwan's avatar
Abdullah Rashwan committed
83
84
85
86
87
    """Cast image to float and run inference.

    Args:
      images: uint8 Tensor of shape [batch_size, None, None, 3]
    Returns:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
88
      Tensor holding detection output logits.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
89
    """
Hongkun Yu's avatar
Hongkun Yu committed
90
    model_params = self.params.task.model
Abdullah Rashwan's avatar
Abdullah Rashwan committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    with tf.device('cpu:0'):
      images = tf.cast(images, dtype=tf.float32)

      # Tensor Specs for map_fn outputs (images, anchor_boxes, and image_info).
      images_spec = tf.TensorSpec(shape=self._input_image_size + [3],
                                  dtype=tf.float32)

      num_anchors = model_params.anchor.num_scales * len(
          model_params.anchor.aspect_ratios) * 4
      anchor_shapes = []
      for level in range(model_params.min_level, model_params.max_level + 1):
        anchor_level_spec = tf.TensorSpec(
            shape=[
                self._input_image_size[0] // 2**level,
                self._input_image_size[1] // 2**level, num_anchors
            ],
            dtype=tf.float32)
        anchor_shapes.append((str(level), anchor_level_spec))

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
110
      image_info_spec = tf.TensorSpec(shape=[4, 2], dtype=tf.float32)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
111

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
112
      images, anchor_boxes, image_info = tf.nest.map_structure(
Abdullah Rashwan's avatar
Abdullah Rashwan committed
113
114
115
116
117
          tf.identity,
          tf.map_fn(
              self._build_inputs,
              elems=images,
              fn_output_signature=(images_spec, dict(anchor_shapes),
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
118
                                   image_info_spec),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
119
120
              parallel_iterations=32))

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
121
122
    input_image_shape = image_info[:, 1, :]

Hongkun Yu's avatar
Hongkun Yu committed
123
    detections = self.model.call(
Abdullah Rashwan's avatar
Abdullah Rashwan committed
124
        images=images,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
125
        image_shape=input_image_shape,
Abdullah Rashwan's avatar
Abdullah Rashwan committed
126
127
128
129
130
131
132
        anchor_boxes=anchor_boxes,
        training=False)

    final_outputs = {
        'detection_boxes': detections['detection_boxes'],
        'detection_scores': detections['detection_scores'],
        'detection_classes': detections['detection_classes'],
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
133
134
        'num_detections': detections['num_detections'],
        'image_info': image_info
Abdullah Rashwan's avatar
Abdullah Rashwan committed
135
136
    }
    if 'detection_masks' in detections.keys():
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
137
      final_outputs['detection_masks'] = detections['detection_masks']
Abdullah Rashwan's avatar
Abdullah Rashwan committed
138
139

    return final_outputs