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.

253 lines
9.4 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. """Box Head.
  16. Contains Box prediction head classes for different meta architectures.
  17. All the box prediction heads have a predict function that receives the
  18. `features` as the first argument and returns `box_encodings`.
  19. """
  20. import functools
  21. import tensorflow as tf
  22. from object_detection.predictors.heads import head
  23. slim = tf.contrib.slim
  24. class MaskRCNNBoxHead(head.Head):
  25. """Box prediction head.
  26. Please refer to Mask RCNN paper:
  27. https://arxiv.org/abs/1703.06870
  28. """
  29. def __init__(self,
  30. is_training,
  31. num_classes,
  32. fc_hyperparams_fn,
  33. use_dropout,
  34. dropout_keep_prob,
  35. box_code_size,
  36. share_box_across_classes=False):
  37. """Constructor.
  38. Args:
  39. is_training: Indicates whether the BoxPredictor is in training mode.
  40. num_classes: number of classes. Note that num_classes *does not*
  41. include the background category, so if groundtruth labels take values
  42. in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the
  43. assigned classification targets can range from {0,... K}).
  44. fc_hyperparams_fn: A function to generate tf-slim arg_scope with
  45. hyperparameters for fully connected ops.
  46. use_dropout: Option to use dropout or not. Note that a single dropout
  47. op is applied here prior to both box and class predictions, which stands
  48. in contrast to the ConvolutionalBoxPredictor below.
  49. dropout_keep_prob: Keep probability for dropout.
  50. This is only used if use_dropout is True.
  51. box_code_size: Size of encoding for each box.
  52. share_box_across_classes: Whether to share boxes across classes rather
  53. than use a different box for each class.
  54. """
  55. super(MaskRCNNBoxHead, self).__init__()
  56. self._is_training = is_training
  57. self._num_classes = num_classes
  58. self._fc_hyperparams_fn = fc_hyperparams_fn
  59. self._use_dropout = use_dropout
  60. self._dropout_keep_prob = dropout_keep_prob
  61. self._box_code_size = box_code_size
  62. self._share_box_across_classes = share_box_across_classes
  63. def predict(self, features, num_predictions_per_location=1):
  64. """Predicts boxes.
  65. Args:
  66. features: A float tensor of shape [batch_size, height, width,
  67. channels] containing features for a batch of images.
  68. num_predictions_per_location: Int containing number of predictions per
  69. location.
  70. Returns:
  71. box_encodings: A float tensor of shape
  72. [batch_size, 1, num_classes, code_size] representing the location of the
  73. objects.
  74. Raises:
  75. ValueError: If num_predictions_per_location is not 1.
  76. """
  77. if num_predictions_per_location != 1:
  78. raise ValueError('Only num_predictions_per_location=1 is supported')
  79. spatial_averaged_roi_pooled_features = tf.reduce_mean(
  80. features, [1, 2], keep_dims=True, name='AvgPool')
  81. flattened_roi_pooled_features = slim.flatten(
  82. spatial_averaged_roi_pooled_features)
  83. if self._use_dropout:
  84. flattened_roi_pooled_features = slim.dropout(
  85. flattened_roi_pooled_features,
  86. keep_prob=self._dropout_keep_prob,
  87. is_training=self._is_training)
  88. number_of_boxes = 1
  89. if not self._share_box_across_classes:
  90. number_of_boxes = self._num_classes
  91. with slim.arg_scope(self._fc_hyperparams_fn()):
  92. box_encodings = slim.fully_connected(
  93. flattened_roi_pooled_features,
  94. number_of_boxes * self._box_code_size,
  95. activation_fn=None,
  96. scope='BoxEncodingPredictor')
  97. box_encodings = tf.reshape(box_encodings,
  98. [-1, 1, number_of_boxes, self._box_code_size])
  99. return box_encodings
  100. class ConvolutionalBoxHead(head.Head):
  101. """Convolutional box prediction head."""
  102. def __init__(self,
  103. is_training,
  104. box_code_size,
  105. kernel_size,
  106. use_depthwise=False):
  107. """Constructor.
  108. Args:
  109. is_training: Indicates whether the BoxPredictor is in training mode.
  110. box_code_size: Size of encoding for each box.
  111. kernel_size: Size of final convolution kernel. If the
  112. spatial resolution of the feature map is smaller than the kernel size,
  113. then the kernel size is automatically set to be
  114. min(feature_width, feature_height).
  115. use_depthwise: Whether to use depthwise convolutions for prediction
  116. steps. Default is False.
  117. Raises:
  118. ValueError: if min_depth > max_depth.
  119. """
  120. super(ConvolutionalBoxHead, self).__init__()
  121. self._is_training = is_training
  122. self._box_code_size = box_code_size
  123. self._kernel_size = kernel_size
  124. self._use_depthwise = use_depthwise
  125. def predict(self, features, num_predictions_per_location):
  126. """Predicts boxes.
  127. Args:
  128. features: A float tensor of shape [batch_size, height, width, channels]
  129. containing image features.
  130. num_predictions_per_location: Number of box predictions to be made per
  131. spatial location. Int specifying number of boxes per location.
  132. Returns:
  133. box_encodings: A float tensors of shape
  134. [batch_size, num_anchors, q, code_size] representing the location of
  135. the objects, where q is 1 or the number of classes.
  136. """
  137. net = features
  138. if self._use_depthwise:
  139. box_encodings = slim.separable_conv2d(
  140. net, None, [self._kernel_size, self._kernel_size],
  141. padding='SAME', depth_multiplier=1, stride=1,
  142. rate=1, scope='BoxEncodingPredictor_depthwise')
  143. box_encodings = slim.conv2d(
  144. box_encodings,
  145. num_predictions_per_location * self._box_code_size, [1, 1],
  146. activation_fn=None,
  147. normalizer_fn=None,
  148. normalizer_params=None,
  149. scope='BoxEncodingPredictor')
  150. else:
  151. box_encodings = slim.conv2d(
  152. net, num_predictions_per_location * self._box_code_size,
  153. [self._kernel_size, self._kernel_size],
  154. activation_fn=None,
  155. normalizer_fn=None,
  156. normalizer_params=None,
  157. scope='BoxEncodingPredictor')
  158. batch_size = features.get_shape().as_list()[0]
  159. if batch_size is None:
  160. batch_size = tf.shape(features)[0]
  161. box_encodings = tf.reshape(box_encodings,
  162. [batch_size, -1, 1, self._box_code_size])
  163. return box_encodings
  164. # TODO(alirezafathi): See if possible to unify Weight Shared with regular
  165. # convolutional box head.
  166. class WeightSharedConvolutionalBoxHead(head.Head):
  167. """Weight shared convolutional box prediction head.
  168. This head allows sharing the same set of parameters (weights) when called more
  169. then once on different feature maps.
  170. """
  171. def __init__(self,
  172. box_code_size,
  173. kernel_size=3,
  174. use_depthwise=False,
  175. box_encodings_clip_range=None):
  176. """Constructor.
  177. Args:
  178. box_code_size: Size of encoding for each box.
  179. kernel_size: Size of final convolution kernel.
  180. use_depthwise: Whether to use depthwise convolutions for prediction steps.
  181. Default is False.
  182. box_encodings_clip_range: Min and max values for clipping box_encodings.
  183. """
  184. super(WeightSharedConvolutionalBoxHead, self).__init__()
  185. self._box_code_size = box_code_size
  186. self._kernel_size = kernel_size
  187. self._use_depthwise = use_depthwise
  188. self._box_encodings_clip_range = box_encodings_clip_range
  189. def predict(self, features, num_predictions_per_location):
  190. """Predicts boxes.
  191. Args:
  192. features: A float tensor of shape [batch_size, height, width, channels]
  193. containing image features.
  194. num_predictions_per_location: Number of box predictions to be made per
  195. spatial location.
  196. Returns:
  197. box_encodings: A float tensor of shape
  198. [batch_size, num_anchors, code_size] representing the location of
  199. the objects.
  200. """
  201. box_encodings_net = features
  202. if self._use_depthwise:
  203. conv_op = functools.partial(slim.separable_conv2d, depth_multiplier=1)
  204. else:
  205. conv_op = slim.conv2d
  206. box_encodings = conv_op(
  207. box_encodings_net,
  208. num_predictions_per_location * self._box_code_size,
  209. [self._kernel_size, self._kernel_size],
  210. activation_fn=None, stride=1, padding='SAME',
  211. normalizer_fn=None,
  212. scope='BoxPredictor')
  213. batch_size = features.get_shape().as_list()[0]
  214. if batch_size is None:
  215. batch_size = tf.shape(features)[0]
  216. # Clipping the box encodings to make the inference graph TPU friendly.
  217. if self._box_encodings_clip_range is not None:
  218. box_encodings = tf.clip_by_value(
  219. box_encodings, self._box_encodings_clip_range.min,
  220. self._box_encodings_clip_range.max)
  221. box_encodings = tf.reshape(box_encodings,
  222. [batch_size, -1, self._box_code_size])
  223. return box_encodings