ops.py 49 KB

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