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.

1090 lines
44 KiB

  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. """A module for helper tensorflow ops."""
  16. import collections
  17. import math
  18. import six
  19. import tensorflow as tf
  20. from object_detection.core import standard_fields as fields
  21. from object_detection.utils import shape_utils
  22. from object_detection.utils import spatial_transform_ops as spatial_ops
  23. from object_detection.utils import static_shape
  24. matmul_crop_and_resize = spatial_ops.matmul_crop_and_resize
  25. multilevel_roi_align = spatial_ops.multilevel_roi_align
  26. native_crop_and_resize = spatial_ops.native_crop_and_resize
  27. def expanded_shape(orig_shape, start_dim, num_dims):
  28. """Inserts multiple ones into a shape vector.
  29. Inserts an all-1 vector of length num_dims at position start_dim into a shape.
  30. Can be combined with tf.reshape to generalize tf.expand_dims.
  31. Args:
  32. orig_shape: the shape into which the all-1 vector is added (int32 vector)
  33. start_dim: insertion position (int scalar)
  34. num_dims: length of the inserted all-1 vector (int scalar)
  35. Returns:
  36. An int32 vector of length tf.size(orig_shape) + num_dims.
  37. """
  38. with tf.name_scope('ExpandedShape'):
  39. start_dim = tf.expand_dims(start_dim, 0) # scalar to rank-1
  40. before = tf.slice(orig_shape, [0], start_dim)
  41. add_shape = tf.ones(tf.reshape(num_dims, [1]), dtype=tf.int32)
  42. after = tf.slice(orig_shape, start_dim, [-1])
  43. new_shape = tf.concat([before, add_shape, after], 0)
  44. return new_shape
  45. def normalized_to_image_coordinates(normalized_boxes, image_shape,
  46. parallel_iterations=32):
  47. """Converts a batch of boxes from normal to image coordinates.
  48. Args:
  49. normalized_boxes: a tensor of shape [None, num_boxes, 4] in
  50. normalized coordinates. The dtype of this tensor must support tf.mul.
  51. image_shape: a tensor of shape [4] containing the image shape, with same
  52. dtype as `normalized_boxes`.
  53. parallel_iterations: parallelism for the map_fn op.
  54. Returns:
  55. absolute_boxes: a tensor of shape [None, num_boxes, 4] containing
  56. the boxes in image coordinates, with same
  57. dtype as `normalized_boxes`.
  58. """
  59. x_scale = tf.cast(image_shape[2], normalized_boxes.dtype)
  60. y_scale = tf.cast(image_shape[1], normalized_boxes.dtype)
  61. def _to_absolute_coordinates(normalized_boxes):
  62. y_min, x_min, y_max, x_max = tf.split(
  63. value=normalized_boxes, num_or_size_splits=4, axis=1)
  64. y_min = y_scale * y_min
  65. y_max = y_scale * y_max
  66. x_min = x_scale * x_min
  67. x_max = x_scale * x_max
  68. scaled_boxes = tf.concat([y_min, x_min, y_max, x_max], 1)
  69. return scaled_boxes
  70. absolute_boxes = shape_utils.static_or_dynamic_map_fn(
  71. _to_absolute_coordinates,
  72. elems=(normalized_boxes),
  73. dtype=normalized_boxes.dtype,
  74. parallel_iterations=parallel_iterations,
  75. back_prop=True)
  76. return absolute_boxes
  77. def meshgrid(x, y):
  78. """Tiles the contents of x and y into a pair of grids.
  79. Multidimensional analog of numpy.meshgrid, giving the same behavior if x and y
  80. are vectors. Generally, this will give:
  81. xgrid(i1, ..., i_m, j_1, ..., j_n) = x(j_1, ..., j_n)
  82. ygrid(i1, ..., i_m, j_1, ..., j_n) = y(i_1, ..., i_m)
  83. Keep in mind that the order of the arguments and outputs is reverse relative
  84. to the order of the indices they go into, done for compatibility with numpy.
  85. The output tensors have the same shapes. Specifically:
  86. xgrid.get_shape() = y.get_shape().concatenate(x.get_shape())
  87. ygrid.get_shape() = y.get_shape().concatenate(x.get_shape())
  88. Args:
  89. x: A tensor of arbitrary shape and rank. xgrid will contain these values
  90. varying in its last dimensions.
  91. y: A tensor of arbitrary shape and rank. ygrid will contain these values
  92. varying in its first dimensions.
  93. Returns:
  94. A tuple of tensors (xgrid, ygrid).
  95. """
  96. with tf.name_scope('Meshgrid'):
  97. x = tf.convert_to_tensor(x)
  98. y = tf.convert_to_tensor(y)
  99. x_exp_shape = expanded_shape(tf.shape(x), 0, tf.rank(y))
  100. y_exp_shape = expanded_shape(tf.shape(y), tf.rank(y), tf.rank(x))
  101. xgrid = tf.tile(tf.reshape(x, x_exp_shape), y_exp_shape)
  102. ygrid = tf.tile(tf.reshape(y, y_exp_shape), x_exp_shape)
  103. new_shape = y.get_shape().concatenate(x.get_shape())
  104. xgrid.set_shape(new_shape)
  105. ygrid.set_shape(new_shape)
  106. return xgrid, ygrid
  107. def fixed_padding(inputs, kernel_size, rate=1):
  108. """Pads the input along the spatial dimensions independently of input size.
  109. Args:
  110. inputs: A tensor of size [batch, height_in, width_in, channels].
  111. kernel_size: The kernel to be used in the conv2d or max_pool2d operation.
  112. Should be a positive integer.
  113. rate: An integer, rate for atrous convolution.
  114. Returns:
  115. output: A tensor of size [batch, height_out, width_out, channels] with the
  116. input, either intact (if kernel_size == 1) or padded (if kernel_size > 1).
  117. """
  118. kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
  119. pad_total = kernel_size_effective - 1
  120. pad_beg = pad_total // 2
  121. pad_end = pad_total - pad_beg
  122. padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end],
  123. [pad_beg, pad_end], [0, 0]])
  124. return padded_inputs
  125. def pad_to_multiple(tensor, multiple):
  126. """Returns the tensor zero padded to the specified multiple.
  127. Appends 0s to the end of the first and second dimension (height and width) of
  128. the tensor until both dimensions are a multiple of the input argument
  129. 'multiple'. E.g. given an input tensor of shape [1, 3, 5, 1] and an input
  130. multiple of 4, PadToMultiple will append 0s so that the resulting tensor will
  131. be of shape [1, 4, 8, 1].
  132. Args:
  133. tensor: rank 4 float32 tensor, where
  134. tensor -> [batch_size, height, width, channels].
  135. multiple: the multiple to pad to.
  136. Returns:
  137. padded_tensor: the tensor zero padded to the specified multiple.
  138. """
  139. if multiple == 1:
  140. return tensor
  141. tensor_shape = tensor.get_shape()
  142. batch_size = static_shape.get_batch_size(tensor_shape)
  143. tensor_height = static_shape.get_height(tensor_shape)
  144. tensor_width = static_shape.get_width(tensor_shape)
  145. tensor_depth = static_shape.get_depth(tensor_shape)
  146. if batch_size is None:
  147. batch_size = tf.shape(tensor)[0]
  148. if tensor_height is None:
  149. tensor_height = tf.shape(tensor)[1]
  150. padded_tensor_height = tf.cast(
  151. tf.ceil(
  152. tf.cast(tensor_height, dtype=tf.float32) /
  153. tf.cast(multiple, dtype=tf.float32)),
  154. dtype=tf.int32) * multiple
  155. else:
  156. padded_tensor_height = int(
  157. math.ceil(float(tensor_height) / multiple) * multiple)
  158. if tensor_width is None:
  159. tensor_width = tf.shape(tensor)[2]
  160. padded_tensor_width = tf.cast(
  161. tf.ceil(
  162. tf.cast(tensor_width, dtype=tf.float32) /
  163. tf.cast(multiple, dtype=tf.float32)),
  164. dtype=tf.int32) * multiple
  165. else:
  166. padded_tensor_width = int(
  167. math.ceil(float(tensor_width) / multiple) * multiple)
  168. if tensor_depth is None:
  169. tensor_depth = tf.shape(tensor)[3]
  170. # Use tf.concat instead of tf.pad to preserve static shape
  171. if padded_tensor_height != tensor_height:
  172. height_pad = tf.zeros([
  173. batch_size, padded_tensor_height - tensor_height, tensor_width,
  174. tensor_depth
  175. ])
  176. tensor = tf.concat([tensor, height_pad], 1)
  177. if padded_tensor_width != tensor_width:
  178. width_pad = tf.zeros([
  179. batch_size, padded_tensor_height, padded_tensor_width - tensor_width,
  180. tensor_depth
  181. ])
  182. tensor = tf.concat([tensor, width_pad], 2)
  183. return tensor
  184. def padded_one_hot_encoding(indices, depth, left_pad):
  185. """Returns a zero padded one-hot tensor.
  186. This function converts a sparse representation of indices (e.g., [4]) to a
  187. zero padded one-hot representation (e.g., [0, 0, 0, 0, 1] with depth = 4 and
  188. left_pad = 1). If `indices` is empty, the result will simply be a tensor of
  189. shape (0, depth + left_pad). If depth = 0, then this function just returns
  190. `None`.
  191. Args:
  192. indices: an integer tensor of shape [num_indices].
  193. depth: depth for the one-hot tensor (integer).
  194. left_pad: number of zeros to left pad the one-hot tensor with (integer).
  195. Returns:
  196. padded_onehot: a tensor with shape (num_indices, depth + left_pad). Returns
  197. `None` if the depth is zero.
  198. Raises:
  199. ValueError: if `indices` does not have rank 1 or if `left_pad` or `depth are
  200. either negative or non-integers.
  201. TODO(rathodv): add runtime checks for depth and indices.
  202. """
  203. if depth < 0 or not isinstance(depth, six.integer_types):
  204. raise ValueError('`depth` must be a non-negative integer.')
  205. if left_pad < 0 or not isinstance(left_pad, six.integer_types):
  206. raise ValueError('`left_pad` must be a non-negative integer.')
  207. if depth == 0:
  208. return None
  209. rank = len(indices.get_shape().as_list())
  210. if rank != 1:
  211. raise ValueError('`indices` must have rank 1, but has rank=%s' % rank)
  212. def one_hot_and_pad():
  213. one_hot = tf.cast(tf.one_hot(tf.cast(indices, tf.int64), depth,
  214. on_value=1, off_value=0), tf.float32)
  215. return tf.pad(one_hot, [[0, 0], [left_pad, 0]], mode='CONSTANT')
  216. result = tf.cond(tf.greater(tf.size(indices), 0), one_hot_and_pad,
  217. lambda: tf.zeros((depth + left_pad, 0)))
  218. return tf.reshape(result, [-1, depth + left_pad])
  219. def dense_to_sparse_boxes(dense_locations, dense_num_boxes, num_classes):
  220. """Converts bounding boxes from dense to sparse form.
  221. Args:
  222. dense_locations: a [max_num_boxes, 4] tensor in which only the first k rows
  223. are valid bounding box location coordinates, where k is the sum of
  224. elements in dense_num_boxes.
  225. dense_num_boxes: a [max_num_classes] tensor indicating the counts of
  226. various bounding box classes e.g. [1, 0, 0, 2] means that the first
  227. bounding box is of class 0 and the second and third bounding boxes are
  228. of class 3. The sum of elements in this tensor is the number of valid
  229. bounding boxes.
  230. num_classes: number of classes
  231. Returns:
  232. box_locations: a [num_boxes, 4] tensor containing only valid bounding
  233. boxes (i.e. the first num_boxes rows of dense_locations)
  234. box_classes: a [num_boxes] tensor containing the classes of each bounding
  235. box (e.g. dense_num_boxes = [1, 0, 0, 2] => box_classes = [0, 3, 3]
  236. """
  237. num_valid_boxes = tf.reduce_sum(dense_num_boxes)
  238. box_locations = tf.slice(dense_locations,
  239. tf.constant([0, 0]), tf.stack([num_valid_boxes, 4]))
  240. tiled_classes = [tf.tile([i], tf.expand_dims(dense_num_boxes[i], 0))
  241. for i in range(num_classes)]
  242. box_classes = tf.concat(tiled_classes, 0)
  243. box_locations.set_shape([None, 4])
  244. return box_locations, box_classes
  245. def indices_to_dense_vector(indices,
  246. size,
  247. indices_value=1.,
  248. default_value=0,
  249. dtype=tf.float32):
  250. """Creates dense vector with indices set to specific value and rest to zeros.
  251. This function exists because it is unclear if it is safe to use
  252. tf.sparse_to_dense(indices, [size], 1, validate_indices=False)
  253. with indices which are not ordered.
  254. This function accepts a dynamic size (e.g. tf.shape(tensor)[0])
  255. Args:
  256. indices: 1d Tensor with integer indices which are to be set to
  257. indices_values.
  258. size: scalar with size (integer) of output Tensor.
  259. indices_value: values of elements specified by indices in the output vector
  260. default_value: values of other elements in the output vector.
  261. dtype: data type.
  262. Returns:
  263. dense 1D Tensor of shape [size] with indices set to indices_values and the
  264. rest set to default_value.
  265. """
  266. size = tf.cast(size, dtype=tf.int32)
  267. zeros = tf.ones([size], dtype=dtype) * default_value
  268. values = tf.ones_like(indices, dtype=dtype) * indices_value
  269. return tf.dynamic_stitch([tf.range(size), tf.cast(indices, dtype=tf.int32)],
  270. [zeros, values])
  271. def reduce_sum_trailing_dimensions(tensor, ndims):
  272. """Computes sum across all dimensions following first `ndims` dimensions."""
  273. return tf.reduce_sum(tensor, axis=tuple(range(ndims, tensor.shape.ndims)))
  274. def retain_groundtruth(tensor_dict, valid_indices):
  275. """Retains groundtruth by valid indices.
  276. Args:
  277. tensor_dict: a dictionary of following groundtruth tensors -
  278. fields.InputDataFields.groundtruth_boxes
  279. fields.InputDataFields.groundtruth_classes
  280. fields.InputDataFields.groundtruth_confidences
  281. fields.InputDataFields.groundtruth_keypoints
  282. fields.InputDataFields.groundtruth_instance_masks
  283. fields.InputDataFields.groundtruth_is_crowd
  284. fields.InputDataFields.groundtruth_area
  285. fields.InputDataFields.groundtruth_label_types
  286. fields.InputDataFields.groundtruth_difficult
  287. valid_indices: a tensor with valid indices for the box-level groundtruth.
  288. Returns:
  289. a dictionary of tensors containing only the groundtruth for valid_indices.
  290. Raises:
  291. ValueError: If the shape of valid_indices is invalid.
  292. ValueError: field fields.InputDataFields.groundtruth_boxes is
  293. not present in tensor_dict.
  294. """
  295. input_shape = valid_indices.get_shape().as_list()
  296. if not (len(input_shape) == 1 or
  297. (len(input_shape) == 2 and input_shape[1] == 1)):
  298. raise ValueError('The shape of valid_indices is invalid.')
  299. valid_indices = tf.reshape(valid_indices, [-1])
  300. valid_dict = {}
  301. if fields.InputDataFields.groundtruth_boxes in tensor_dict:
  302. # Prevents reshape failure when num_boxes is 0.
  303. num_boxes = tf.maximum(tf.shape(
  304. tensor_dict[fields.InputDataFields.groundtruth_boxes])[0], 1)
  305. for key in tensor_dict:
  306. if key in [fields.InputDataFields.groundtruth_boxes,
  307. fields.InputDataFields.groundtruth_classes,
  308. fields.InputDataFields.groundtruth_confidences,
  309. fields.InputDataFields.groundtruth_keypoints,
  310. fields.InputDataFields.groundtruth_keypoint_visibilities,
  311. fields.InputDataFields.groundtruth_instance_masks]:
  312. valid_dict[key] = tf.gather(tensor_dict[key], valid_indices)
  313. # Input decoder returns empty tensor when these fields are not provided.
  314. # Needs to reshape into [num_boxes, -1] for tf.gather() to work.
  315. elif key in [fields.InputDataFields.groundtruth_is_crowd,
  316. fields.InputDataFields.groundtruth_area,
  317. fields.InputDataFields.groundtruth_difficult,
  318. fields.InputDataFields.groundtruth_label_types]:
  319. valid_dict[key] = tf.reshape(
  320. tf.gather(tf.reshape(tensor_dict[key], [num_boxes, -1]),
  321. valid_indices), [-1])
  322. # Fields that are not associated with boxes.
  323. else:
  324. valid_dict[key] = tensor_dict[key]
  325. else:
  326. raise ValueError('%s not present in input tensor dict.' % (
  327. fields.InputDataFields.groundtruth_boxes))
  328. return valid_dict
  329. def retain_groundtruth_with_positive_classes(tensor_dict):
  330. """Retains only groundtruth with positive class ids.
  331. Args:
  332. tensor_dict: a dictionary of following groundtruth tensors -
  333. fields.InputDataFields.groundtruth_boxes
  334. fields.InputDataFields.groundtruth_classes
  335. fields.InputDataFields.groundtruth_confidences
  336. fields.InputDataFields.groundtruth_keypoints
  337. fields.InputDataFields.groundtruth_instance_masks
  338. fields.InputDataFields.groundtruth_is_crowd
  339. fields.InputDataFields.groundtruth_area
  340. fields.InputDataFields.groundtruth_label_types
  341. fields.InputDataFields.groundtruth_difficult
  342. Returns:
  343. a dictionary of tensors containing only the groundtruth with positive
  344. classes.
  345. Raises:
  346. ValueError: If groundtruth_classes tensor is not in tensor_dict.
  347. """
  348. if fields.InputDataFields.groundtruth_classes not in tensor_dict:
  349. raise ValueError('`groundtruth classes` not in tensor_dict.')
  350. keep_indices = tf.where(tf.greater(
  351. tensor_dict[fields.InputDataFields.groundtruth_classes], 0))
  352. return retain_groundtruth(tensor_dict, keep_indices)
  353. def replace_nan_groundtruth_label_scores_with_ones(label_scores):
  354. """Replaces nan label scores with 1.0.
  355. Args:
  356. label_scores: a tensor containing object annoation label scores.
  357. Returns:
  358. a tensor where NaN label scores have been replaced by ones.
  359. """
  360. return tf.where(
  361. tf.is_nan(label_scores), tf.ones(tf.shape(label_scores)), label_scores)
  362. def filter_groundtruth_with_crowd_boxes(tensor_dict):
  363. """Filters out groundtruth with boxes corresponding to crowd.
  364. Args:
  365. tensor_dict: a dictionary of following groundtruth tensors -
  366. fields.InputDataFields.groundtruth_boxes
  367. fields.InputDataFields.groundtruth_classes
  368. fields.InputDataFields.groundtruth_confidences
  369. fields.InputDataFields.groundtruth_keypoints
  370. fields.InputDataFields.groundtruth_instance_masks
  371. fields.InputDataFields.groundtruth_is_crowd
  372. fields.InputDataFields.groundtruth_area
  373. fields.InputDataFields.groundtruth_label_types
  374. Returns:
  375. a dictionary of tensors containing only the groundtruth that have bounding
  376. boxes.
  377. """
  378. if fields.InputDataFields.groundtruth_is_crowd in tensor_dict:
  379. is_crowd = tensor_dict[fields.InputDataFields.groundtruth_is_crowd]
  380. is_not_crowd = tf.logical_not(is_crowd)
  381. is_not_crowd_indices = tf.where(is_not_crowd)
  382. tensor_dict = retain_groundtruth(tensor_dict, is_not_crowd_indices)
  383. return tensor_dict
  384. def filter_groundtruth_with_nan_box_coordinates(tensor_dict):
  385. """Filters out groundtruth with no bounding boxes.
  386. Args:
  387. tensor_dict: a dictionary of following groundtruth tensors -
  388. fields.InputDataFields.groundtruth_boxes
  389. fields.InputDataFields.groundtruth_classes
  390. fields.InputDataFields.groundtruth_confidences
  391. fields.InputDataFields.groundtruth_keypoints
  392. fields.InputDataFields.groundtruth_instance_masks
  393. fields.InputDataFields.groundtruth_is_crowd
  394. fields.InputDataFields.groundtruth_area
  395. fields.InputDataFields.groundtruth_label_types
  396. Returns:
  397. a dictionary of tensors containing only the groundtruth that have bounding
  398. boxes.
  399. """
  400. groundtruth_boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes]
  401. nan_indicator_vector = tf.greater(tf.reduce_sum(tf.cast(
  402. tf.is_nan(groundtruth_boxes), dtype=tf.int32), reduction_indices=[1]), 0)
  403. valid_indicator_vector = tf.logical_not(nan_indicator_vector)
  404. valid_indices = tf.where(valid_indicator_vector)
  405. return retain_groundtruth(tensor_dict, valid_indices)
  406. def filter_unrecognized_classes(tensor_dict):
  407. """Filters out class labels that are not unrecognized by the labelmap.
  408. Decoder would parse unrecognized classes (not included in the labelmap) to
  409. a label of value -1. Such targets are unecessary for training, and causes
  410. issue for evaluation, due to labeling mapping logic. This function filters
  411. those labels out for both training and evaluation.
  412. Args:
  413. tensor_dict: dictionary containing input tensors keyed by
  414. fields.InputDataFields.
  415. Returns:
  416. A dictionary keyed by fields.InputDataFields containing the tensors
  417. obtained after applying the filtering.
  418. Raises:
  419. ValueError: If groundtruth_classes tensor is not in tensor_dict.
  420. """
  421. if fields.InputDataFields.groundtruth_classes not in tensor_dict:
  422. raise ValueError('`groundtruth classes` not in tensor_dict.')
  423. # Refer to tf_example_decoder for how unrecognized labels are handled.
  424. unrecognized_label = -1
  425. recognized_indices = tf.where(
  426. tf.greater(tensor_dict[fields.InputDataFields.groundtruth_classes],
  427. unrecognized_label))
  428. return retain_groundtruth(tensor_dict, recognized_indices)
  429. def normalize_to_target(inputs,
  430. target_norm_value,
  431. dim,
  432. epsilon=1e-7,
  433. trainable=True,
  434. scope='NormalizeToTarget',
  435. summarize=True):
  436. """L2 normalizes the inputs across the specified dimension to a target norm.
  437. This op implements the L2 Normalization layer introduced in
  438. Liu, Wei, et al. "SSD: Single Shot MultiBox Detector."
  439. and Liu, Wei, Andrew Rabinovich, and Alexander C. Berg.
  440. "Parsenet: Looking wider to see better." and is useful for bringing
  441. activations from multiple layers in a convnet to a standard scale.
  442. Note that the rank of `inputs` must be known and the dimension to which
  443. normalization is to be applied should be statically defined.
  444. TODO(jonathanhuang): Add option to scale by L2 norm of the entire input.
  445. Args:
  446. inputs: A `Tensor` of arbitrary size.
  447. target_norm_value: A float value that specifies an initial target norm or
  448. a list of floats (whose length must be equal to the depth along the
  449. dimension to be normalized) specifying a per-dimension multiplier
  450. after normalization.
  451. dim: The dimension along which the input is normalized.
  452. epsilon: A small value to add to the inputs to avoid dividing by zero.
  453. trainable: Whether the norm is trainable or not
  454. scope: Optional scope for variable_scope.
  455. summarize: Whether or not to add a tensorflow summary for the op.
  456. Returns:
  457. The input tensor normalized to the specified target norm.
  458. Raises:
  459. ValueError: If dim is smaller than the number of dimensions in 'inputs'.
  460. ValueError: If target_norm_value is not a float or a list of floats with
  461. length equal to the depth along the dimension to be normalized.
  462. """
  463. with tf.variable_scope(scope, 'NormalizeToTarget', [inputs]):
  464. if not inputs.get_shape():
  465. raise ValueError('The input rank must be known.')
  466. input_shape = inputs.get_shape().as_list()
  467. input_rank = len(input_shape)
  468. if dim < 0 or dim >= input_rank:
  469. raise ValueError(
  470. 'dim must be non-negative but smaller than the input rank.')
  471. if not input_shape[dim]:
  472. raise ValueError('input shape should be statically defined along '
  473. 'the specified dimension.')
  474. depth = input_shape[dim]
  475. if not (isinstance(target_norm_value, float) or
  476. (isinstance(target_norm_value, list) and
  477. len(target_norm_value) == depth) and
  478. all([isinstance(val, float) for val in target_norm_value])):
  479. raise ValueError('target_norm_value must be a float or a list of floats '
  480. 'with length equal to the depth along the dimension to '
  481. 'be normalized.')
  482. if isinstance(target_norm_value, float):
  483. initial_norm = depth * [target_norm_value]
  484. else:
  485. initial_norm = target_norm_value
  486. target_norm = tf.contrib.framework.model_variable(
  487. name='weights', dtype=tf.float32,
  488. initializer=tf.constant(initial_norm, dtype=tf.float32),
  489. trainable=trainable)
  490. if summarize:
  491. mean = tf.reduce_mean(target_norm)
  492. tf.summary.scalar(tf.get_variable_scope().name, mean)
  493. lengths = epsilon + tf.sqrt(tf.reduce_sum(tf.square(inputs), dim, True))
  494. mult_shape = input_rank*[1]
  495. mult_shape[dim] = depth
  496. return tf.reshape(target_norm, mult_shape) * tf.truediv(inputs, lengths)
  497. def batch_position_sensitive_crop_regions(images,
  498. boxes,
  499. crop_size,
  500. num_spatial_bins,
  501. global_pool,
  502. parallel_iterations=64):
  503. """Position sensitive crop with batches of images and boxes.
  504. This op is exactly like `position_sensitive_crop_regions` below but operates
  505. on batches of images and boxes. See `position_sensitive_crop_regions` function
  506. below for the operation applied per batch element.
  507. Args:
  508. images: A `Tensor`. Must be one of the following types: `uint8`, `int8`,
  509. `int16`, `int32`, `int64`, `half`, `float32`, `float64`.
  510. A 4-D tensor of shape `[batch, image_height, image_width, depth]`.
  511. Both `image_height` and `image_width` need to be positive.
  512. boxes: A `Tensor` of type `float32`.
  513. A 3-D tensor of shape `[batch, num_boxes, 4]`. Each box is specified in
  514. normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value
  515. of `y` is mapped to the image coordinate at `y * (image_height - 1)`, so
  516. as the `[0, 1]` interval of normalized image height is mapped to
  517. `[0, image_height - 1] in image height coordinates. We do allow y1 > y2,
  518. in which case the sampled crop is an up-down flipped version of the
  519. original image. The width dimension is treated similarly.
  520. crop_size: See `position_sensitive_crop_regions` below.
  521. num_spatial_bins: See `position_sensitive_crop_regions` below.
  522. global_pool: See `position_sensitive_crop_regions` below.
  523. parallel_iterations: Number of batch items to process in parallel.
  524. Returns:
  525. """
  526. def _position_sensitive_crop_fn(inputs):
  527. images, boxes = inputs
  528. return position_sensitive_crop_regions(
  529. images,
  530. boxes,
  531. crop_size=crop_size,
  532. num_spatial_bins=num_spatial_bins,
  533. global_pool=global_pool)
  534. return shape_utils.static_or_dynamic_map_fn(
  535. _position_sensitive_crop_fn,
  536. elems=[images, boxes],
  537. dtype=tf.float32,
  538. parallel_iterations=parallel_iterations)
  539. def position_sensitive_crop_regions(image,
  540. boxes,
  541. crop_size,
  542. num_spatial_bins,
  543. global_pool):
  544. """Position-sensitive crop and pool rectangular regions from a feature grid.
  545. The output crops are split into `spatial_bins_y` vertical bins
  546. and `spatial_bins_x` horizontal bins. For each intersection of a vertical
  547. and a horizontal bin the output values are gathered by performing
  548. `tf.image.crop_and_resize` (bilinear resampling) on a a separate subset of
  549. channels of the image. This reduces `depth` by a factor of
  550. `(spatial_bins_y * spatial_bins_x)`.
  551. When global_pool is True, this function implements a differentiable version
  552. of position-sensitive RoI pooling used in
  553. [R-FCN detection system](https://arxiv.org/abs/1605.06409).
  554. When global_pool is False, this function implements a differentiable version
  555. of position-sensitive assembling operation used in
  556. [instance FCN](https://arxiv.org/abs/1603.08678).
  557. Args:
  558. image: A `Tensor`. Must be one of the following types: `uint8`, `int8`,
  559. `int16`, `int32`, `int64`, `half`, `float32`, `float64`.
  560. A 3-D tensor of shape `[image_height, image_width, depth]`.
  561. Both `image_height` and `image_width` need to be positive.
  562. boxes: A `Tensor` of type `float32`.
  563. A 2-D tensor of shape `[num_boxes, 4]`. Each box is specified in
  564. normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value
  565. of `y` is mapped to the image coordinate at `y * (image_height - 1)`, so
  566. as the `[0, 1]` interval of normalized image height is mapped to
  567. `[0, image_height - 1] in image height coordinates. We do allow y1 > y2,
  568. in which case the sampled crop is an up-down flipped version of the
  569. original image. The width dimension is treated similarly.
  570. crop_size: A list of two integers `[crop_height, crop_width]`. All
  571. cropped image patches are resized to this size. The aspect ratio of the
  572. image content is not preserved. Both `crop_height` and `crop_width` need
  573. to be positive.
  574. num_spatial_bins: A list of two integers `[spatial_bins_y, spatial_bins_x]`.
  575. Represents the number of position-sensitive bins in y and x directions.
  576. Both values should be >= 1. `crop_height` should be divisible by
  577. `spatial_bins_y`, and similarly for width.
  578. The number of image channels should be divisible by
  579. (spatial_bins_y * spatial_bins_x).
  580. Suggested value from R-FCN paper: [3, 3].
  581. global_pool: A boolean variable.
  582. If True, we perform average global pooling on the features assembled from
  583. the position-sensitive score maps.
  584. If False, we keep the position-pooled features without global pooling
  585. over the spatial coordinates.
  586. Note that using global_pool=True is equivalent to but more efficient than
  587. running the function with global_pool=False and then performing global
  588. average pooling.
  589. Returns:
  590. position_sensitive_features: A 4-D tensor of shape
  591. `[num_boxes, K, K, crop_channels]`,
  592. where `crop_channels = depth / (spatial_bins_y * spatial_bins_x)`,
  593. where K = 1 when global_pool is True (Average-pooled cropped regions),
  594. and K = crop_size when global_pool is False.
  595. Raises:
  596. ValueError: Raised in four situations:
  597. `num_spatial_bins` is not >= 1;
  598. `num_spatial_bins` does not divide `crop_size`;
  599. `(spatial_bins_y*spatial_bins_x)` does not divide `depth`;
  600. `bin_crop_size` is not square when global_pool=False due to the
  601. constraint in function space_to_depth.
  602. """
  603. total_bins = 1
  604. bin_crop_size = []
  605. for (num_bins, crop_dim) in zip(num_spatial_bins, crop_size):
  606. if num_bins < 1:
  607. raise ValueError('num_spatial_bins should be >= 1')
  608. if crop_dim % num_bins != 0:
  609. raise ValueError('crop_size should be divisible by num_spatial_bins')
  610. total_bins *= num_bins
  611. bin_crop_size.append(crop_dim // num_bins)
  612. if not global_pool and bin_crop_size[0] != bin_crop_size[1]:
  613. raise ValueError('Only support square bin crop size for now.')
  614. ymin, xmin, ymax, xmax = tf.unstack(boxes, axis=1)
  615. spatial_bins_y, spatial_bins_x = num_spatial_bins
  616. # Split each box into spatial_bins_y * spatial_bins_x bins.
  617. position_sensitive_boxes = []
  618. for bin_y in range(spatial_bins_y):
  619. step_y = (ymax - ymin) / spatial_bins_y
  620. for bin_x in range(spatial_bins_x):
  621. step_x = (xmax - xmin) / spatial_bins_x
  622. box_coordinates = [ymin + bin_y * step_y,
  623. xmin + bin_x * step_x,
  624. ymin + (bin_y + 1) * step_y,
  625. xmin + (bin_x + 1) * step_x,
  626. ]
  627. position_sensitive_boxes.append(tf.stack(box_coordinates, axis=1))
  628. image_splits = tf.split(value=image, num_or_size_splits=total_bins, axis=2)
  629. image_crops = []
  630. for (split, box) in zip(image_splits, position_sensitive_boxes):
  631. if split.shape.is_fully_defined() and box.shape.is_fully_defined():
  632. crop = tf.squeeze(
  633. matmul_crop_and_resize(
  634. tf.expand_dims(split, axis=0), tf.expand_dims(box, axis=0),
  635. bin_crop_size),
  636. axis=0)
  637. else:
  638. crop = tf.image.crop_and_resize(
  639. tf.expand_dims(split, 0), box,
  640. tf.zeros(tf.shape(boxes)[0], dtype=tf.int32), bin_crop_size)
  641. image_crops.append(crop)
  642. if global_pool:
  643. # Average over all bins.
  644. position_sensitive_features = tf.add_n(image_crops) / len(image_crops)
  645. # Then average over spatial positions within the bins.
  646. position_sensitive_features = tf.reduce_mean(
  647. position_sensitive_features, [1, 2], keepdims=True)
  648. else:
  649. # Reorder height/width to depth channel.
  650. block_size = bin_crop_size[0]
  651. if block_size >= 2:
  652. image_crops = [tf.space_to_depth(
  653. crop, block_size=block_size) for crop in image_crops]
  654. # Pack image_crops so that first dimension is for position-senstive boxes.
  655. position_sensitive_features = tf.stack(image_crops, axis=0)
  656. # Unroll the position-sensitive boxes to spatial positions.
  657. position_sensitive_features = tf.squeeze(
  658. tf.batch_to_space_nd(position_sensitive_features,
  659. block_shape=[1] + num_spatial_bins,
  660. crops=tf.zeros((3, 2), dtype=tf.int32)),
  661. axis=[0])
  662. # Reorder back the depth channel.
  663. if block_size >= 2:
  664. position_sensitive_features = tf.depth_to_space(
  665. position_sensitive_features, block_size=block_size)
  666. return position_sensitive_features
  667. def reframe_box_masks_to_image_masks(box_masks, boxes, image_height,
  668. image_width):
  669. """Transforms the box masks back to full image masks.
  670. Embeds masks in bounding boxes of larger masks whose shapes correspond to
  671. image shape.
  672. Args:
  673. box_masks: A tf.float32 tensor of size [num_masks, mask_height, mask_width].
  674. boxes: A tf.float32 tensor of size [num_masks, 4] containing the box
  675. corners. Row i contains [ymin, xmin, ymax, xmax] of the box
  676. corresponding to mask i. Note that the box corners are in
  677. normalized coordinates.
  678. image_height: Image height. The output mask will have the same height as
  679. the image height.
  680. image_width: Image width. The output mask will have the same width as the
  681. image width.
  682. Returns:
  683. A tf.float32 tensor of size [num_masks, image_height, image_width].
  684. """
  685. # TODO(rathodv): Make this a public function.
  686. def reframe_box_masks_to_image_masks_default():
  687. """The default function when there are more than 0 box masks."""
  688. def transform_boxes_relative_to_boxes(boxes, reference_boxes):
  689. boxes = tf.reshape(boxes, [-1, 2, 2])
  690. min_corner = tf.expand_dims(reference_boxes[:, 0:2], 1)
  691. max_corner = tf.expand_dims(reference_boxes[:, 2:4], 1)
  692. transformed_boxes = (boxes - min_corner) / (max_corner - min_corner)
  693. return tf.reshape(transformed_boxes, [-1, 4])
  694. box_masks_expanded = tf.expand_dims(box_masks, axis=3)
  695. num_boxes = tf.shape(box_masks_expanded)[0]
  696. unit_boxes = tf.concat(
  697. [tf.zeros([num_boxes, 2]), tf.ones([num_boxes, 2])], axis=1)
  698. reverse_boxes = transform_boxes_relative_to_boxes(unit_boxes, boxes)
  699. return tf.image.crop_and_resize(
  700. image=box_masks_expanded,
  701. boxes=reverse_boxes,
  702. box_ind=tf.range(num_boxes),
  703. crop_size=[image_height, image_width],
  704. extrapolation_value=0.0)
  705. image_masks = tf.cond(
  706. tf.shape(box_masks)[0] > 0,
  707. reframe_box_masks_to_image_masks_default,
  708. lambda: tf.zeros([0, image_height, image_width, 1], dtype=tf.float32))
  709. return tf.squeeze(image_masks, axis=3)
  710. def merge_boxes_with_multiple_labels(boxes,
  711. classes,
  712. confidences,
  713. num_classes,
  714. quantization_bins=10000):
  715. """Merges boxes with same coordinates and returns K-hot encoded classes.
  716. Args:
  717. boxes: A tf.float32 tensor with shape [N, 4] holding N boxes. Only
  718. normalized coordinates are allowed.
  719. classes: A tf.int32 tensor with shape [N] holding class indices.
  720. The class index starts at 0.
  721. confidences: A tf.float32 tensor with shape [N] holding class confidences.
  722. num_classes: total number of classes to use for K-hot encoding.
  723. quantization_bins: the number of bins used to quantize the box coordinate.
  724. Returns:
  725. merged_boxes: A tf.float32 tensor with shape [N', 4] holding boxes,
  726. where N' <= N.
  727. class_encodings: A tf.int32 tensor with shape [N', num_classes] holding
  728. K-hot encodings for the merged boxes.
  729. confidence_encodings: A tf.float32 tensor with shape [N', num_classes]
  730. holding encodings of confidences for the merged boxes.
  731. merged_box_indices: A tf.int32 tensor with shape [N'] holding original
  732. indices of the boxes.
  733. """
  734. boxes_shape = tf.shape(boxes)
  735. classes_shape = tf.shape(classes)
  736. confidences_shape = tf.shape(confidences)
  737. box_class_shape_assert = shape_utils.assert_shape_equal_along_first_dimension(
  738. boxes_shape, classes_shape)
  739. box_confidence_shape_assert = (
  740. shape_utils.assert_shape_equal_along_first_dimension(
  741. boxes_shape, confidences_shape))
  742. box_dimension_assert = tf.assert_equal(boxes_shape[1], 4)
  743. box_normalized_assert = shape_utils.assert_box_normalized(boxes)
  744. with tf.control_dependencies(
  745. [box_class_shape_assert, box_confidence_shape_assert,
  746. box_dimension_assert, box_normalized_assert]):
  747. quantized_boxes = tf.to_int64(boxes * (quantization_bins - 1))
  748. ymin, xmin, ymax, xmax = tf.unstack(quantized_boxes, axis=1)
  749. hashcodes = (
  750. ymin +
  751. xmin * quantization_bins +
  752. ymax * quantization_bins * quantization_bins +
  753. xmax * quantization_bins * quantization_bins * quantization_bins)
  754. unique_hashcodes, unique_indices = tf.unique(hashcodes)
  755. num_boxes = tf.shape(boxes)[0]
  756. num_unique_boxes = tf.shape(unique_hashcodes)[0]
  757. merged_box_indices = tf.unsorted_segment_min(
  758. tf.range(num_boxes), unique_indices, num_unique_boxes)
  759. merged_boxes = tf.gather(boxes, merged_box_indices)
  760. unique_indices = tf.to_int64(unique_indices)
  761. classes = tf.to_int64(classes)
  762. def map_box_encodings(i):
  763. """Produces box K-hot and score encodings for each class index."""
  764. box_mask = tf.equal(
  765. unique_indices, i * tf.ones(num_boxes, dtype=tf.int64))
  766. box_mask = tf.reshape(box_mask, [-1])
  767. box_indices = tf.boolean_mask(classes, box_mask)
  768. box_confidences = tf.boolean_mask(confidences, box_mask)
  769. box_class_encodings = tf.sparse_to_dense(
  770. box_indices, [num_classes], tf.constant(1, dtype=tf.int64),
  771. validate_indices=False)
  772. box_confidence_encodings = tf.sparse_to_dense(
  773. box_indices, [num_classes], box_confidences, validate_indices=False)
  774. return box_class_encodings, box_confidence_encodings
  775. # Important to avoid int32 here since there is no GPU kernel for int32.
  776. # int64 and float32 are fine.
  777. class_encodings, confidence_encodings = tf.map_fn(
  778. map_box_encodings,
  779. tf.range(tf.to_int64(num_unique_boxes)),
  780. back_prop=False,
  781. dtype=(tf.int64, tf.float32))
  782. merged_boxes = tf.reshape(merged_boxes, [-1, 4])
  783. class_encodings = tf.cast(class_encodings, dtype=tf.int32)
  784. class_encodings = tf.reshape(class_encodings, [-1, num_classes])
  785. confidence_encodings = tf.reshape(confidence_encodings, [-1, num_classes])
  786. merged_box_indices = tf.reshape(merged_box_indices, [-1])
  787. return (merged_boxes, class_encodings, confidence_encodings,
  788. merged_box_indices)
  789. def nearest_neighbor_upsampling(input_tensor, scale=None, height_scale=None,
  790. width_scale=None):
  791. """Nearest neighbor upsampling implementation.
  792. Nearest neighbor upsampling function that maps input tensor with shape
  793. [batch_size, height, width, channels] to [batch_size, height * scale
  794. , width * scale, channels]. This implementation only uses reshape and
  795. broadcasting to make it TPU compatible.
  796. Args:
  797. input_tensor: A float32 tensor of size [batch, height_in, width_in,
  798. channels].
  799. scale: An integer multiple to scale resolution of input data in both height
  800. and width dimensions.
  801. height_scale: An integer multiple to scale the height of input image. This
  802. option when provided overrides `scale` option.
  803. width_scale: An integer multiple to scale the width of input image. This
  804. option when provided overrides `scale` option.
  805. Returns:
  806. data_up: A float32 tensor of size
  807. [batch, height_in*scale, width_in*scale, channels].
  808. Raises:
  809. ValueError: If both scale and height_scale or if both scale and width_scale
  810. are None.
  811. """
  812. if not scale and (height_scale is None or width_scale is None):
  813. raise ValueError('Provide either `scale` or `height_scale` and'
  814. ' `width_scale`.')
  815. with tf.name_scope('nearest_neighbor_upsampling'):
  816. h_scale = scale if height_scale is None else height_scale
  817. w_scale = scale if width_scale is None else width_scale
  818. (batch_size, height, width,
  819. channels) = shape_utils.combined_static_and_dynamic_shape(input_tensor)
  820. output_tensor = tf.reshape(
  821. input_tensor, [batch_size, height, 1, width, 1, channels]) * tf.ones(
  822. [1, 1, h_scale, 1, w_scale, 1], dtype=input_tensor.dtype)
  823. return tf.reshape(output_tensor,
  824. [batch_size, height * h_scale, width * w_scale, channels])
  825. def matmul_gather_on_zeroth_axis(params, indices, scope=None):
  826. """Matrix multiplication based implementation of tf.gather on zeroth axis.
  827. TODO(rathodv, jonathanhuang): enable sparse matmul option.
  828. Args:
  829. params: A float32 Tensor. The tensor from which to gather values.
  830. Must be at least rank 1.
  831. indices: A Tensor. Must be one of the following types: int32, int64.
  832. Must be in range [0, params.shape[0])
  833. scope: A name for the operation (optional).
  834. Returns:
  835. A Tensor. Has the same type as params. Values from params gathered
  836. from indices given by indices, with shape indices.shape + params.shape[1:].
  837. """
  838. with tf.name_scope(scope, 'MatMulGather'):
  839. params_shape = shape_utils.combined_static_and_dynamic_shape(params)
  840. indices_shape = shape_utils.combined_static_and_dynamic_shape(indices)
  841. params2d = tf.reshape(params, [params_shape[0], -1])
  842. indicator_matrix = tf.one_hot(indices, params_shape[0])
  843. gathered_result_flattened = tf.matmul(indicator_matrix, params2d)
  844. return tf.reshape(gathered_result_flattened,
  845. tf.stack(indices_shape + params_shape[1:]))
  846. def fpn_feature_levels(num_levels, unit_scale_index, image_ratio, boxes):
  847. """Returns fpn feature level for each box based on its area.
  848. See section 4.2 of https://arxiv.org/pdf/1612.03144.pdf for details.
  849. Args:
  850. num_levels: An integer indicating the number of feature levels to crop boxes
  851. from.
  852. unit_scale_index: An 0-based integer indicating the index of feature map
  853. which most closely matches the resolution of the pretrained model.
  854. image_ratio: A float indicating the ratio of input image area to pretraining
  855. image area.
  856. boxes: A float tensor of shape [batch, num_boxes, 4] containing boxes of the
  857. form [ymin, xmin, ymax, xmax] in normalized coordinates.
  858. Returns:
  859. An int32 tensor of shape [batch_size, num_boxes] containing feature indices.
  860. """
  861. assert num_levels > 0, (
  862. '`num_levels` must be > 0. Found {}'.format(num_levels))
  863. assert unit_scale_index < num_levels and unit_scale_index >= 0, (
  864. '`unit_scale_index` must be in [0, {}). Found {}.'.format(
  865. num_levels, unit_scale_index))
  866. box_height_width = boxes[:, :, 2:4] - boxes[:, :, 0:2]
  867. areas_sqrt = tf.sqrt(tf.reduce_prod(box_height_width, axis=2))
  868. log_2 = tf.cast(tf.log(2.0), dtype=boxes.dtype)
  869. levels = tf.cast(
  870. tf.floordiv(tf.log(areas_sqrt * image_ratio), log_2)
  871. +
  872. unit_scale_index,
  873. dtype=tf.int32)
  874. levels = tf.maximum(0, tf.minimum(num_levels - 1, levels))
  875. return levels
  876. def bfloat16_to_float32_nested(tensor_nested):
  877. """Convert float32 tensors in a nested structure to bfloat16.
  878. Args:
  879. tensor_nested: A Python dict, values being Tensor or Python list/tuple of
  880. Tensor.
  881. Returns:
  882. A Python dict with the same structure as `tensor_dict`,
  883. with all bfloat16 tensors converted to float32.
  884. """
  885. if isinstance(tensor_nested, tf.Tensor):
  886. if tensor_nested.dtype == tf.bfloat16:
  887. return tf.cast(tensor_nested, dtype=tf.float32)
  888. else:
  889. return tensor_nested
  890. elif isinstance(tensor_nested, (list, tuple)):
  891. out_tensor_dict = [bfloat16_to_float32_nested(t) for t in tensor_nested]
  892. elif isinstance(tensor_nested, dict):
  893. out_tensor_dict = {
  894. k: bfloat16_to_float32_nested(v) for k, v in tensor_nested.items()
  895. }
  896. return out_tensor_dict
  897. def gather_with_padding_values(input_tensor, indices, padding_value):
  898. """Gathers elements from tensor and pads `padding_value` for ignore indices.
  899. Gathers elements from `input_tensor` based on `indices`. If there are ignore
  900. indices (which are "-1"s) in `indices`, `padding_value` will be gathered for
  901. those positions.
  902. Args:
  903. input_tensor: A N-D tensor of shape [M, d_1, d_2 .. d_(N-1)] to gather
  904. values from.
  905. indices: A 1-D tensor in which each element is either an index in the
  906. first dimension of input_tensor or -1.
  907. padding_value: A (N-1)-D tensor of shape [d_1, d_2 .. d_(N-1)] which will be
  908. used as gathered value for each ignore index in `indices`.
  909. Returns:
  910. gathered_tensor: A tensor of shape [L, d_1, d_2 .. d_(N-1)] containing
  911. values gathered from input_tensor. The first dimension L is equal to the
  912. length of `indices`.
  913. """
  914. padding_value = tf.expand_dims(padding_value, axis=0)
  915. input_tensor = tf.concat([padding_value, input_tensor], axis=0)
  916. gather_indices = indices + 1
  917. gathered_tensor = tf.gather(input_tensor, gather_indices)
  918. return gathered_tensor
  919. EqualizationLossConfig = collections.namedtuple('EqualizationLossConfig',
  920. ['weight', 'exclude_prefixes'])