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.

229 lines
7.6 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. """Contains functions which are convenient for unit testing."""
  16. import numpy as np
  17. import tensorflow as tf
  18. from object_detection.core import anchor_generator
  19. from object_detection.core import box_coder
  20. from object_detection.core import box_list
  21. from object_detection.core import box_predictor
  22. from object_detection.core import matcher
  23. from object_detection.utils import shape_utils
  24. # Default size (both width and height) used for testing mask predictions.
  25. DEFAULT_MASK_SIZE = 5
  26. class MockBoxCoder(box_coder.BoxCoder):
  27. """Simple `difference` BoxCoder."""
  28. @property
  29. def code_size(self):
  30. return 4
  31. def _encode(self, boxes, anchors):
  32. return boxes.get() - anchors.get()
  33. def _decode(self, rel_codes, anchors):
  34. return box_list.BoxList(rel_codes + anchors.get())
  35. class MockMaskHead(object):
  36. """Simple maskhead that returns all zeros as mask predictions."""
  37. def __init__(self, num_classes):
  38. self._num_classes = num_classes
  39. def predict(self, features):
  40. batch_size = tf.shape(features)[0]
  41. return tf.zeros((batch_size, 1, self._num_classes, DEFAULT_MASK_SIZE,
  42. DEFAULT_MASK_SIZE),
  43. dtype=tf.float32)
  44. class MockBoxPredictor(box_predictor.BoxPredictor):
  45. """Simple box predictor that ignores inputs and outputs all zeros."""
  46. def __init__(self, is_training, num_classes, add_background_class=True):
  47. super(MockBoxPredictor, self).__init__(is_training, num_classes)
  48. self._add_background_class = add_background_class
  49. def _predict(self, image_features, num_predictions_per_location):
  50. image_feature = image_features[0]
  51. combined_feature_shape = shape_utils.combined_static_and_dynamic_shape(
  52. image_feature)
  53. batch_size = combined_feature_shape[0]
  54. num_anchors = (combined_feature_shape[1] * combined_feature_shape[2])
  55. code_size = 4
  56. zero = tf.reduce_sum(0 * image_feature)
  57. num_class_slots = self.num_classes
  58. if self._add_background_class:
  59. num_class_slots = num_class_slots + 1
  60. box_encodings = zero + tf.zeros(
  61. (batch_size, num_anchors, 1, code_size), dtype=tf.float32)
  62. class_predictions_with_background = zero + tf.zeros(
  63. (batch_size, num_anchors, num_class_slots), dtype=tf.float32)
  64. predictions_dict = {
  65. box_predictor.BOX_ENCODINGS:
  66. box_encodings,
  67. box_predictor.CLASS_PREDICTIONS_WITH_BACKGROUND:
  68. class_predictions_with_background
  69. }
  70. return predictions_dict
  71. class MockKerasBoxPredictor(box_predictor.KerasBoxPredictor):
  72. """Simple box predictor that ignores inputs and outputs all zeros."""
  73. def __init__(self, is_training, num_classes, add_background_class=True):
  74. super(MockKerasBoxPredictor, self).__init__(
  75. is_training, num_classes, False, False)
  76. self._add_background_class = add_background_class
  77. def _predict(self, image_features, **kwargs):
  78. image_feature = image_features[0]
  79. combined_feature_shape = shape_utils.combined_static_and_dynamic_shape(
  80. image_feature)
  81. batch_size = combined_feature_shape[0]
  82. num_anchors = (combined_feature_shape[1] * combined_feature_shape[2])
  83. code_size = 4
  84. zero = tf.reduce_sum(0 * image_feature)
  85. num_class_slots = self.num_classes
  86. if self._add_background_class:
  87. num_class_slots = num_class_slots + 1
  88. box_encodings = zero + tf.zeros(
  89. (batch_size, num_anchors, 1, code_size), dtype=tf.float32)
  90. class_predictions_with_background = zero + tf.zeros(
  91. (batch_size, num_anchors, num_class_slots), dtype=tf.float32)
  92. predictions_dict = {
  93. box_predictor.BOX_ENCODINGS:
  94. box_encodings,
  95. box_predictor.CLASS_PREDICTIONS_WITH_BACKGROUND:
  96. class_predictions_with_background
  97. }
  98. return predictions_dict
  99. class MockAnchorGenerator(anchor_generator.AnchorGenerator):
  100. """Mock anchor generator."""
  101. def name_scope(self):
  102. return 'MockAnchorGenerator'
  103. def num_anchors_per_location(self):
  104. return [1]
  105. def _generate(self, feature_map_shape_list):
  106. num_anchors = sum([shape[0] * shape[1] for shape in feature_map_shape_list])
  107. return box_list.BoxList(tf.zeros((num_anchors, 4), dtype=tf.float32))
  108. class MockMatcher(matcher.Matcher):
  109. """Simple matcher that matches first anchor to first groundtruth box."""
  110. def _match(self, similarity_matrix, valid_rows):
  111. return tf.constant([0, -1, -1, -1], dtype=tf.int32)
  112. def create_diagonal_gradient_image(height, width, depth):
  113. """Creates pyramid image. Useful for testing.
  114. For example, pyramid_image(5, 6, 1) looks like:
  115. # [[[ 5. 4. 3. 2. 1. 0.]
  116. # [ 6. 5. 4. 3. 2. 1.]
  117. # [ 7. 6. 5. 4. 3. 2.]
  118. # [ 8. 7. 6. 5. 4. 3.]
  119. # [ 9. 8. 7. 6. 5. 4.]]]
  120. Args:
  121. height: height of image
  122. width: width of image
  123. depth: depth of image
  124. Returns:
  125. pyramid image
  126. """
  127. row = np.arange(height)
  128. col = np.arange(width)[::-1]
  129. image_layer = np.expand_dims(row, 1) + col
  130. image_layer = np.expand_dims(image_layer, 2)
  131. image = image_layer
  132. for i in range(1, depth):
  133. image = np.concatenate((image, image_layer * pow(10, i)), 2)
  134. return image.astype(np.float32)
  135. def create_random_boxes(num_boxes, max_height, max_width):
  136. """Creates random bounding boxes of specific maximum height and width.
  137. Args:
  138. num_boxes: number of boxes.
  139. max_height: maximum height of boxes.
  140. max_width: maximum width of boxes.
  141. Returns:
  142. boxes: numpy array of shape [num_boxes, 4]. Each row is in form
  143. [y_min, x_min, y_max, x_max].
  144. """
  145. y_1 = np.random.uniform(size=(1, num_boxes)) * max_height
  146. y_2 = np.random.uniform(size=(1, num_boxes)) * max_height
  147. x_1 = np.random.uniform(size=(1, num_boxes)) * max_width
  148. x_2 = np.random.uniform(size=(1, num_boxes)) * max_width
  149. boxes = np.zeros(shape=(num_boxes, 4))
  150. boxes[:, 0] = np.minimum(y_1, y_2)
  151. boxes[:, 1] = np.minimum(x_1, x_2)
  152. boxes[:, 2] = np.maximum(y_1, y_2)
  153. boxes[:, 3] = np.maximum(x_1, x_2)
  154. return boxes.astype(np.float32)
  155. def first_rows_close_as_set(a, b, k=None, rtol=1e-6, atol=1e-6):
  156. """Checks if first K entries of two lists are close, up to permutation.
  157. Inputs to this assert are lists of items which can be compared via
  158. numpy.allclose(...) and can be sorted.
  159. Args:
  160. a: list of items which can be compared via numpy.allclose(...) and are
  161. sortable.
  162. b: list of items which can be compared via numpy.allclose(...) and are
  163. sortable.
  164. k: a non-negative integer. If not provided, k is set to be len(a).
  165. rtol: relative tolerance.
  166. atol: absolute tolerance.
  167. Returns:
  168. boolean, True if input lists a and b have the same length and
  169. the first k entries of the inputs satisfy numpy.allclose() after
  170. sorting entries.
  171. """
  172. if not isinstance(a, list) or not isinstance(b, list) or len(a) != len(b):
  173. return False
  174. if not k:
  175. k = len(a)
  176. k = min(k, len(a))
  177. a_sorted = sorted(a[:k])
  178. b_sorted = sorted(b[:k])
  179. return all([
  180. np.allclose(entry_a, entry_b, rtol, atol)
  181. for (entry_a, entry_b) in zip(a_sorted, b_sorted)
  182. ])