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.

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