target_ops.py 27.7 KB
Newer Older
Yeqing Li's avatar
Yeqing Li committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Pengchong Jin's avatar
Pengchong Jin committed
2
3
4
5
6
7
8
9
10
11
12
13
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Yeqing Li's avatar
Yeqing Li committed
14

15
"""Target and sampling related ops."""
Pengchong Jin's avatar
Pengchong Jin committed
16
17
18
19
20

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

21
import tensorflow as tf
Pengchong Jin's avatar
Pengchong Jin committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

from official.vision.detection.ops import spatial_transform_ops
from official.vision.detection.utils import box_utils
from official.vision.detection.utils.object_detection import balanced_positive_negative_sampler


def box_matching(boxes, gt_boxes, gt_classes):
  """Match boxes to groundtruth boxes.

  Given the proposal boxes and the groundtruth boxes and classes, perform the
  groundtruth matching by taking the argmax of the IoU between boxes and
  groundtruth boxes.

  Args:
    boxes: a tensor of shape of [batch_size, N, 4] representing the box
      coordiantes to be matched to groundtruth boxes.
    gt_boxes: a tensor of shape of [batch_size, MAX_INSTANCES, 4] representing
      the groundtruth box coordinates. It is padded with -1s to indicate the
      invalid boxes.
    gt_classes: [batch_size, MAX_INSTANCES] representing the groundtruth box
      classes. It is padded with -1s to indicate the invalid classes.

  Returns:
    matched_gt_boxes: a tensor of shape of [batch_size, N, 4], representing
      the matched groundtruth box coordinates for each input box. If the box
      does not overlap with any groundtruth boxes, the matched boxes of it
      will be set to all 0s.
    matched_gt_classes: a tensor of shape of [batch_size, N], representing
      the matched groundtruth classes for each input box. If the box does not
      overlap with any groundtruth boxes, the matched box classes of it will
      be set to 0, which corresponds to the background class.
    matched_gt_indices: a tensor of shape of [batch_size, N], representing
      the indices of the matched groundtruth boxes in the original gt_boxes
      tensor. If the box does not overlap with any groundtruth boxes, the
      index of the matched groundtruth will be set to -1.
    matched_iou: a tensor of shape of [batch_size, N], representing the IoU
      between the box and its matched groundtruth box. The matched IoU is the
      maximum IoU of the box and all the groundtruth boxes.
    iou: a tensor of shape of [batch_size, N, K], representing the IoU matrix
      between boxes and the groundtruth boxes. The IoU between a box and the
      invalid groundtruth boxes whose coordinates are [-1, -1, -1, -1] is -1.
  """
  # Compute IoU between boxes and gt_boxes.
  # iou <- [batch_size, N, K]
  iou = box_utils.bbox_overlap(boxes, gt_boxes)

  # max_iou <- [batch_size, N]
  # 0.0 -> no match to gt, or -1.0 match to no gt
  matched_iou = tf.reduce_max(iou, axis=-1)

  # background_box_mask <- bool, [batch_size, N]
  background_box_mask = tf.less_equal(matched_iou, 0.0)

  argmax_iou_indices = tf.argmax(iou, axis=-1, output_type=tf.int32)

  argmax_iou_indices_shape = tf.shape(argmax_iou_indices)
  batch_indices = (
      tf.expand_dims(tf.range(argmax_iou_indices_shape[0]), axis=-1) *
      tf.ones([1, argmax_iou_indices_shape[-1]], dtype=tf.int32))
  gather_nd_indices = tf.stack([batch_indices, argmax_iou_indices], axis=-1)

  matched_gt_boxes = tf.gather_nd(gt_boxes, gather_nd_indices)
  matched_gt_boxes = tf.where(
      tf.tile(tf.expand_dims(background_box_mask, axis=-1), [1, 1, 4]),
Yeqing Li's avatar
Yeqing Li committed
86
      tf.zeros_like(matched_gt_boxes, dtype=matched_gt_boxes.dtype),
Pengchong Jin's avatar
Pengchong Jin committed
87
88
89
      matched_gt_boxes)

  matched_gt_classes = tf.gather_nd(gt_classes, gather_nd_indices)
Hongkun Yu's avatar
Hongkun Yu committed
90
91
92
  matched_gt_classes = tf.where(background_box_mask,
                                tf.zeros_like(matched_gt_classes),
                                matched_gt_classes)
Pengchong Jin's avatar
Pengchong Jin committed
93

Hongkun Yu's avatar
Hongkun Yu committed
94
95
96
  matched_gt_indices = tf.where(background_box_mask,
                                -tf.ones_like(argmax_iou_indices),
                                argmax_iou_indices)
Pengchong Jin's avatar
Pengchong Jin committed
97

Hongkun Yu's avatar
Hongkun Yu committed
98
99
  return (matched_gt_boxes, matched_gt_classes, matched_gt_indices, matched_iou,
          iou)
Pengchong Jin's avatar
Pengchong Jin committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121


def assign_and_sample_proposals(proposed_boxes,
                                gt_boxes,
                                gt_classes,
                                num_samples_per_image=512,
                                mix_gt_boxes=True,
                                fg_fraction=0.25,
                                fg_iou_thresh=0.5,
                                bg_iou_thresh_hi=0.5,
                                bg_iou_thresh_lo=0.0):
  """Assigns the proposals with groundtruth classes and performs subsmpling.

  Given `proposed_boxes`, `gt_boxes`, and `gt_classes`, the function uses the
  following algorithm to generate the final `num_samples_per_image` RoIs.
    1. Calculates the IoU between each proposal box and each gt_boxes.
    2. Assigns each proposed box with a groundtruth class and box by choosing
       the largest IoU overlap.
    3. Samples `num_samples_per_image` boxes from all proposed boxes, and
       returns box_targets, class_targets, and RoIs.

  Args:
Hongkun Yu's avatar
Hongkun Yu committed
122
123
124
125
126
127
128
    proposed_boxes: a tensor of shape of [batch_size, N, 4]. N is the number of
      proposals before groundtruth assignment. The last dimension is the box
      coordinates w.r.t. the scaled images in [ymin, xmin, ymax, xmax] format.
    gt_boxes: a tensor of shape of [batch_size, MAX_NUM_INSTANCES, 4]. The
      coordinates of gt_boxes are in the pixel coordinates of the scaled image.
      This tensor might have padding of values -1 indicating the invalid box
      coordinates.
Pengchong Jin's avatar
Pengchong Jin committed
129
130
131
132
133
134
    gt_classes: a tensor with a shape of [batch_size, MAX_NUM_INSTANCES]. This
      tensor might have paddings with values of -1 indicating the invalid
      classes.
    num_samples_per_image: a integer represents RoI minibatch size per image.
    mix_gt_boxes: a bool indicating whether to mix the groundtruth boxes before
      sampling proposals.
Hongkun Yu's avatar
Hongkun Yu committed
135
136
    fg_fraction: a float represents the target fraction of RoI minibatch that is
      labeled foreground (i.e., class > 0).
Pengchong Jin's avatar
Pengchong Jin committed
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    fg_iou_thresh: a float represents the IoU overlap threshold for an RoI to be
      considered foreground (if >= fg_iou_thresh).
    bg_iou_thresh_hi: a float represents the IoU overlap threshold for an RoI to
      be considered background (class = 0 if overlap in [LO, HI)).
    bg_iou_thresh_lo: a float represents the IoU overlap threshold for an RoI to
      be considered background (class = 0 if overlap in [LO, HI)).

  Returns:
    sampled_rois: a tensor of shape of [batch_size, K, 4], representing the
      coordinates of the sampled RoIs, where K is the number of the sampled
      RoIs, i.e. K = num_samples_per_image.
    sampled_gt_boxes: a tensor of shape of [batch_size, K, 4], storing the
      box coordinates of the matched groundtruth boxes of the samples RoIs.
    sampled_gt_classes: a tensor of shape of [batch_size, K], storing the
      classes of the matched groundtruth boxes of the sampled RoIs.
    sampled_gt_indices: a tensor of shape of [batch_size, K], storing the
      indices of the sampled groudntruth boxes in the original `gt_boxes`
      tensor, i.e. gt_boxes[sampled_gt_indices[:, i]] = sampled_gt_boxes[:, i].
  """

  with tf.name_scope('sample_proposals'):
    if mix_gt_boxes:
      boxes = tf.concat([proposed_boxes, gt_boxes], axis=1)
    else:
      boxes = proposed_boxes

Hongkun Yu's avatar
Hongkun Yu committed
163
164
    (matched_gt_boxes, matched_gt_classes, matched_gt_indices, matched_iou,
     _) = box_matching(boxes, gt_boxes, gt_classes)
Pengchong Jin's avatar
Pengchong Jin committed
165
166
167
168
169
170
171
172

    positive_match = tf.greater(matched_iou, fg_iou_thresh)
    negative_match = tf.logical_and(
        tf.greater_equal(matched_iou, bg_iou_thresh_lo),
        tf.less(matched_iou, bg_iou_thresh_hi))
    ignored_match = tf.less(matched_iou, 0.0)

    # re-assign negatively matched boxes to the background class.
Hongkun Yu's avatar
Hongkun Yu committed
173
174
175
176
177
178
    matched_gt_classes = tf.where(negative_match,
                                  tf.zeros_like(matched_gt_classes),
                                  matched_gt_classes)
    matched_gt_indices = tf.where(negative_match,
                                  tf.zeros_like(matched_gt_indices),
                                  matched_gt_indices)
Pengchong Jin's avatar
Pengchong Jin committed
179
180
181
182
183
184
185
186
187
188
189
190

    sample_candidates = tf.logical_and(
        tf.logical_or(positive_match, negative_match),
        tf.logical_not(ignored_match))

    sampler = (
        balanced_positive_negative_sampler.BalancedPositiveNegativeSampler(
            positive_fraction=fg_fraction, is_static=True))

    batch_size, _ = sample_candidates.get_shape().as_list()
    sampled_indicators = []
    for i in range(batch_size):
Hongkun Yu's avatar
Hongkun Yu committed
191
192
193
      sampled_indicator = sampler.subsample(sample_candidates[i],
                                            num_samples_per_image,
                                            positive_match[i])
Pengchong Jin's avatar
Pengchong Jin committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
      sampled_indicators.append(sampled_indicator)
    sampled_indicators = tf.stack(sampled_indicators)
    _, sampled_indices = tf.nn.top_k(
        tf.cast(sampled_indicators, dtype=tf.int32),
        k=num_samples_per_image,
        sorted=True)

    sampled_indices_shape = tf.shape(sampled_indices)
    batch_indices = (
        tf.expand_dims(tf.range(sampled_indices_shape[0]), axis=-1) *
        tf.ones([1, sampled_indices_shape[-1]], dtype=tf.int32))
    gather_nd_indices = tf.stack([batch_indices, sampled_indices], axis=-1)

    sampled_rois = tf.gather_nd(boxes, gather_nd_indices)
    sampled_gt_boxes = tf.gather_nd(matched_gt_boxes, gather_nd_indices)
Hongkun Yu's avatar
Hongkun Yu committed
209
210
    sampled_gt_classes = tf.gather_nd(matched_gt_classes, gather_nd_indices)
    sampled_gt_indices = tf.gather_nd(matched_gt_indices, gather_nd_indices)
Pengchong Jin's avatar
Pengchong Jin committed
211
212
213
214
215
216
217
218
219
220

    return (sampled_rois, sampled_gt_boxes, sampled_gt_classes,
            sampled_gt_indices)


def sample_and_crop_foreground_masks(candidate_rois,
                                     candidate_gt_boxes,
                                     candidate_gt_classes,
                                     candidate_gt_indices,
                                     gt_masks,
Pengchong Jin's avatar
Pengchong Jin committed
221
222
                                     num_mask_samples_per_image=128,
                                     mask_target_size=28):
Pengchong Jin's avatar
Pengchong Jin committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
  """Samples and creates cropped foreground masks for training.

  Args:
    candidate_rois: a tensor of shape of [batch_size, N, 4], where N is the
      number of candidate RoIs to be considered for mask sampling. It includes
      both positive and negative RoIs. The `num_mask_samples_per_image` positive
      RoIs will be sampled to create mask training targets.
    candidate_gt_boxes: a tensor of shape of [batch_size, N, 4], storing the
      corresponding groundtruth boxes to the `candidate_rois`.
    candidate_gt_classes: a tensor of shape of [batch_size, N], storing the
      corresponding groundtruth classes to the `candidate_rois`. 0 in the tensor
      corresponds to the background class, i.e. negative RoIs.
    candidate_gt_indices: a tensor of shape [batch_size, N], storing the
      corresponding groundtruth instance indices to the `candidate_gt_boxes`,
      i.e. gt_boxes[candidate_gt_indices[:, i]] = candidate_gt_boxes[:, i] and
Hongkun Yu's avatar
Hongkun Yu committed
238
239
        gt_boxes which is of shape [batch_size, MAX_INSTANCES, 4], M >= N, is
        the superset of candidate_gt_boxes.
Pengchong Jin's avatar
Pengchong Jin committed
240
241
242
243
    gt_masks: a tensor of [batch_size, MAX_INSTANCES, mask_height, mask_width]
      containing all the groundtruth masks which sample masks are drawn from.
    num_mask_samples_per_image: an integer which specifies the number of masks
      to sample.
Pengchong Jin's avatar
Pengchong Jin committed
244
    mask_target_size: an integer which specifies the final cropped mask size
Pengchong Jin's avatar
Pengchong Jin committed
245
246
247
248
249
250
251
252
253
      after sampling. The output masks are resized w.r.t the sampled RoIs.

  Returns:
    foreground_rois: a tensor of shape of [batch_size, K, 4] storing the RoI
      that corresponds to the sampled foreground masks, where
      K = num_mask_samples_per_image.
    foreground_classes: a tensor of shape of [batch_size, K] storing the classes
      corresponding to the sampled foreground masks.
    cropoped_foreground_masks: a tensor of shape of
Pengchong Jin's avatar
Pengchong Jin committed
254
      [batch_size, K, mask_target_size, mask_target_size] storing the cropped
Pengchong Jin's avatar
Pengchong Jin committed
255
256
257
258
259
260
261
262
263
264
265
266
      foreground masks used for training.
  """
  with tf.name_scope('sample_and_crop_foreground_masks'):
    _, fg_instance_indices = tf.nn.top_k(
        tf.cast(tf.greater(candidate_gt_classes, 0), dtype=tf.int32),
        k=num_mask_samples_per_image)

    fg_instance_indices_shape = tf.shape(fg_instance_indices)
    batch_indices = (
        tf.expand_dims(tf.range(fg_instance_indices_shape[0]), axis=-1) *
        tf.ones([1, fg_instance_indices_shape[-1]], dtype=tf.int32))

Hongkun Yu's avatar
Hongkun Yu committed
267
268
269
270
271
272
273
274
275
    gather_nd_instance_indices = tf.stack([batch_indices, fg_instance_indices],
                                          axis=-1)
    foreground_rois = tf.gather_nd(candidate_rois, gather_nd_instance_indices)
    foreground_boxes = tf.gather_nd(candidate_gt_boxes,
                                    gather_nd_instance_indices)
    foreground_classes = tf.gather_nd(candidate_gt_classes,
                                      gather_nd_instance_indices)
    foreground_gt_indices = tf.gather_nd(candidate_gt_indices,
                                         gather_nd_instance_indices)
Pengchong Jin's avatar
Pengchong Jin committed
276

Pengchong Jin's avatar
Pengchong Jin committed
277
    foreground_gt_indices_shape = tf.shape(foreground_gt_indices)
Pengchong Jin's avatar
Pengchong Jin committed
278
    batch_indices = (
Pengchong Jin's avatar
Pengchong Jin committed
279
280
        tf.expand_dims(tf.range(foreground_gt_indices_shape[0]), axis=-1) *
        tf.ones([1, foreground_gt_indices_shape[-1]], dtype=tf.int32))
Hongkun Yu's avatar
Hongkun Yu committed
281
282
    gather_nd_gt_indices = tf.stack([batch_indices, foreground_gt_indices],
                                    axis=-1)
Pengchong Jin's avatar
Pengchong Jin committed
283
284
285
    foreground_masks = tf.gather_nd(gt_masks, gather_nd_gt_indices)

    cropped_foreground_masks = spatial_transform_ops.crop_mask_in_target_box(
Hongkun Yu's avatar
Hongkun Yu committed
286
287
288
289
        foreground_masks,
        foreground_boxes,
        foreground_rois,
        mask_target_size,
Pengchong Jin's avatar
Pengchong Jin committed
290
        sample_offset=0.5)
Pengchong Jin's avatar
Pengchong Jin committed
291
292
293
294

    return foreground_rois, foreground_classes, cropped_foreground_masks


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
295
class ROISampler(tf.keras.layers.Layer):
Pengchong Jin's avatar
Pengchong Jin committed
296
297
298
299
300
301
302
303
304
  """Samples RoIs and creates training targets."""

  def __init__(self, params):
    self._num_samples_per_image = params.num_samples_per_image
    self._fg_fraction = params.fg_fraction
    self._fg_iou_thresh = params.fg_iou_thresh
    self._bg_iou_thresh_hi = params.bg_iou_thresh_hi
    self._bg_iou_thresh_lo = params.bg_iou_thresh_lo
    self._mix_gt_boxes = params.mix_gt_boxes
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
305
    super(ROISampler, self).__init__(autocast=False)
Pengchong Jin's avatar
Pengchong Jin committed
306

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
307
  def call(self, rois, gt_boxes, gt_classes):
Pengchong Jin's avatar
Pengchong Jin committed
308
309
310
    """Sample and assign RoIs for training.

    Args:
Hongkun Yu's avatar
Hongkun Yu committed
311
312
313
314
315
      rois: a tensor of shape of [batch_size, N, 4]. N is the number of
        proposals before groundtruth assignment. The last dimension is the box
        coordinates w.r.t. the scaled images in [ymin, xmin, ymax, xmax] format.
      gt_boxes: a tensor of shape of [batch_size, MAX_NUM_INSTANCES, 4]. The
        coordinates of gt_boxes are in the pixel coordinates of the scaled
Pengchong Jin's avatar
Pengchong Jin committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
        image. This tensor might have padding of values -1 indicating the
        invalid box coordinates.
      gt_classes: a tensor with a shape of [batch_size, MAX_NUM_INSTANCES]. This
        tensor might have paddings with values of -1 indicating the invalid
        classes.

    Returns:
      sampled_rois: a tensor of shape of [batch_size, K, 4], representing the
        coordinates of the sampled RoIs, where K is the number of the sampled
        RoIs, i.e. K = num_samples_per_image.
      sampled_gt_boxes: a tensor of shape of [batch_size, K, 4], storing the
        box coordinates of the matched groundtruth boxes of the samples RoIs.
      sampled_gt_classes: a tensor of shape of [batch_size, K], storing the
        classes of the matched groundtruth boxes of the sampled RoIs.
    """
    sampled_rois, sampled_gt_boxes, sampled_gt_classes, sampled_gt_indices = (
        assign_and_sample_proposals(
            rois,
            gt_boxes,
            gt_classes,
            num_samples_per_image=self._num_samples_per_image,
            mix_gt_boxes=self._mix_gt_boxes,
            fg_fraction=self._fg_fraction,
            fg_iou_thresh=self._fg_iou_thresh,
            bg_iou_thresh_hi=self._bg_iou_thresh_hi,
            bg_iou_thresh_lo=self._bg_iou_thresh_lo))
    return (sampled_rois, sampled_gt_boxes, sampled_gt_classes,
            sampled_gt_indices)


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
class ROIScoreSampler(ROISampler):
  """Samples RoIs, RoI-scores and creates training targets."""

  def __call__(self, rois, roi_scores, gt_boxes, gt_classes):
    """Sample and assign RoIs for training.

    Args:
      rois: a tensor of shape of [batch_size, N, 4]. N is the number of
        proposals before groundtruth assignment. The last dimension is the box
        coordinates w.r.t. the scaled images in [ymin, xmin, ymax, xmax] format.
      roi_scores:
      gt_boxes: a tensor of shape of [batch_size, MAX_NUM_INSTANCES, 4]. The
        coordinates of gt_boxes are in the pixel coordinates of the scaled
        image. This tensor might have padding of values -1 indicating the
        invalid box coordinates.
      gt_classes: a tensor with a shape of [batch_size, MAX_NUM_INSTANCES]. This
        tensor might have paddings with values of -1 indicating the invalid
        classes.

    Returns:
      sampled_rois: a tensor of shape of [batch_size, K, 4], representing the
        coordinates of the sampled RoIs, where K is the number of the sampled
        RoIs, i.e. K = num_samples_per_image.
      sampled_roi_scores:
      sampled_gt_boxes: a tensor of shape of [batch_size, K, 4], storing the
        box coordinates of the matched groundtruth boxes of the samples RoIs.
      sampled_gt_classes: a tensor of shape of [batch_size, K], storing the
        classes of the matched groundtruth boxes of the sampled RoIs.
    """
    (sampled_rois, sampled_roi_scores, sampled_gt_boxes, sampled_gt_classes,
     sampled_gt_indices) = (
         self.assign_and_sample_proposals_and_scores(
             rois,
             roi_scores,
             gt_boxes,
             gt_classes,
             num_samples_per_image=self._num_samples_per_image,
             mix_gt_boxes=self._mix_gt_boxes,
             fg_fraction=self._fg_fraction,
             fg_iou_thresh=self._fg_iou_thresh,
             bg_iou_thresh_hi=self._bg_iou_thresh_hi,
             bg_iou_thresh_lo=self._bg_iou_thresh_lo))
    return (sampled_rois, sampled_roi_scores, sampled_gt_boxes,
            sampled_gt_classes, sampled_gt_indices)

  def assign_and_sample_proposals_and_scores(self,
                                             proposed_boxes,
                                             proposed_scores,
                                             gt_boxes,
                                             gt_classes,
                                             num_samples_per_image=512,
                                             mix_gt_boxes=True,
                                             fg_fraction=0.25,
                                             fg_iou_thresh=0.5,
                                             bg_iou_thresh_hi=0.5,
                                             bg_iou_thresh_lo=0.0):
    """Assigns the proposals with groundtruth classes and performs subsmpling.

    Given `proposed_boxes`, `gt_boxes`, and `gt_classes`, the function uses the
    following algorithm to generate the final `num_samples_per_image` RoIs.
      1. Calculates the IoU between each proposal box and each gt_boxes.
      2. Assigns each proposed box with a groundtruth class and box by choosing
         the largest IoU overlap.
      3. Samples `num_samples_per_image` boxes from all proposed boxes, and
         returns box_targets, class_targets, and RoIs.

    Args:
      proposed_boxes: a tensor of shape of [batch_size, N, 4]. N is the number
        of proposals before groundtruth assignment. The last dimension is the
        box coordinates w.r.t. the scaled images in [ymin, xmin, ymax, xmax]
        format.
      proposed_scores: a tensor of shape of [batch_size, N]. N is the number of
        proposals before groundtruth assignment. It is the rpn scores for all
        proposed boxes which can be either their classification or centerness
        scores.
      gt_boxes: a tensor of shape of [batch_size, MAX_NUM_INSTANCES, 4]. The
        coordinates of gt_boxes are in the pixel coordinates of the scaled
        image. This tensor might have padding of values -1 indicating the
        invalid box coordinates.
      gt_classes: a tensor with a shape of [batch_size, MAX_NUM_INSTANCES]. This
        tensor might have paddings with values of -1 indicating the invalid
        classes.
      num_samples_per_image: a integer represents RoI minibatch size per image.
      mix_gt_boxes: a bool indicating whether to mix the groundtruth boxes
      before sampling proposals.
      fg_fraction: a float represents the target fraction of RoI minibatch that
        is labeled foreground (i.e., class > 0).
      fg_iou_thresh: a float represents the IoU overlap threshold for an RoI to
        be considered foreground (if >= fg_iou_thresh).
      bg_iou_thresh_hi: a float represents the IoU overlap threshold for an RoI
        to be considered background (class = 0 if overlap in [LO, HI)).
      bg_iou_thresh_lo: a float represents the IoU overlap threshold for an RoI
        to be considered background (class = 0 if overlap in [LO, HI)).

    Returns:
      sampled_rois: a tensor of shape of [batch_size, K, 4], representing the
        coordinates of the sampled RoIs, where K is the number of the sampled
        RoIs, i.e. K = num_samples_per_image.
      sampled_scores: a tensor of shape of [batch_size, K], representing the
        confidence score of the sampled RoIs, where K is the number of the
        sampled RoIs, i.e. K = num_samples_per_image.
      sampled_gt_boxes: a tensor of shape of [batch_size, K, 4], storing the
        box coordinates of the matched groundtruth boxes of the samples RoIs.
      sampled_gt_classes: a tensor of shape of [batch_size, K], storing the
        classes of the matched groundtruth boxes of the sampled RoIs.
      sampled_gt_indices: a tensor of shape of [batch_size, K], storing the
        indices of the sampled groudntruth boxes in the original `gt_boxes`
        tensor, i.e. gt_boxes[sampled_gt_indices[:, i]] =
        sampled_gt_boxes[:, i].
    """

    with tf.name_scope('sample_proposals_and_scores'):
      if mix_gt_boxes:
        boxes = tf.concat([proposed_boxes, gt_boxes], axis=1)
        gt_scores = tf.ones_like(gt_boxes[:, :, 0])
        scores = tf.concat([proposed_scores, gt_scores], axis=1)
      else:
        boxes = proposed_boxes
        scores = proposed_scores

      (matched_gt_boxes, matched_gt_classes, matched_gt_indices, matched_iou,
       _) = box_matching(boxes, gt_boxes, gt_classes)

      positive_match = tf.greater(matched_iou, fg_iou_thresh)
      negative_match = tf.logical_and(
          tf.greater_equal(matched_iou, bg_iou_thresh_lo),
          tf.less(matched_iou, bg_iou_thresh_hi))
      ignored_match = tf.less(matched_iou, 0.0)

      # re-assign negatively matched boxes to the background class.
      matched_gt_classes = tf.where(negative_match,
                                    tf.zeros_like(matched_gt_classes),
                                    matched_gt_classes)
      matched_gt_indices = tf.where(negative_match,
                                    tf.zeros_like(matched_gt_indices),
                                    matched_gt_indices)

      sample_candidates = tf.logical_and(
          tf.logical_or(positive_match, negative_match),
          tf.logical_not(ignored_match))

      sampler = (
          balanced_positive_negative_sampler.BalancedPositiveNegativeSampler(
              positive_fraction=fg_fraction, is_static=True))

      batch_size, _ = sample_candidates.get_shape().as_list()
      sampled_indicators = []
      for i in range(batch_size):
        sampled_indicator = sampler.subsample(sample_candidates[i],
                                              num_samples_per_image,
                                              positive_match[i])
        sampled_indicators.append(sampled_indicator)
      sampled_indicators = tf.stack(sampled_indicators)
      _, sampled_indices = tf.nn.top_k(
          tf.cast(sampled_indicators, dtype=tf.int32),
          k=num_samples_per_image,
          sorted=True)

      sampled_indices_shape = tf.shape(sampled_indices)
      batch_indices = (
          tf.expand_dims(tf.range(sampled_indices_shape[0]), axis=-1) *
          tf.ones([1, sampled_indices_shape[-1]], dtype=tf.int32))
      gather_nd_indices = tf.stack([batch_indices, sampled_indices], axis=-1)

      sampled_rois = tf.gather_nd(boxes, gather_nd_indices)
      sampled_roi_scores = tf.gather_nd(scores, gather_nd_indices)
      sampled_gt_boxes = tf.gather_nd(matched_gt_boxes, gather_nd_indices)
      sampled_gt_classes = tf.gather_nd(matched_gt_classes, gather_nd_indices)
      sampled_gt_indices = tf.gather_nd(matched_gt_indices, gather_nd_indices)

      return (sampled_rois, sampled_roi_scores, sampled_gt_boxes,
              sampled_gt_classes, sampled_gt_indices)


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
520
class MaskSampler(tf.keras.layers.Layer):
Pengchong Jin's avatar
Pengchong Jin committed
521
522
  """Samples and creates mask training targets."""

Pengchong Jin's avatar
Pengchong Jin committed
523
524
525
  def __init__(self, mask_target_size, num_mask_samples_per_image):
    self._mask_target_size = mask_target_size
    self._num_mask_samples_per_image = num_mask_samples_per_image
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
526
527
528
529
530
531
532
533
    super(MaskSampler, self).__init__(autocast=False)

  def call(self,
           candidate_rois,
           candidate_gt_boxes,
           candidate_gt_classes,
           candidate_gt_indices,
           gt_masks):
Pengchong Jin's avatar
Pengchong Jin committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
    """Sample and create mask targets for training.

    Args:
      candidate_rois: a tensor of shape of [batch_size, N, 4], where N is the
        number of candidate RoIs to be considered for mask sampling. It includes
        both positive and negative RoIs. The `num_mask_samples_per_image`
        positive RoIs will be sampled to create mask training targets.
      candidate_gt_boxes: a tensor of shape of [batch_size, N, 4], storing the
        corresponding groundtruth boxes to the `candidate_rois`.
      candidate_gt_classes: a tensor of shape of [batch_size, N], storing the
        corresponding groundtruth classes to the `candidate_rois`. 0 in the
        tensor corresponds to the background class, i.e. negative RoIs.
      candidate_gt_indices: a tensor of shape [batch_size, N], storing the
        corresponding groundtruth instance indices to the `candidate_gt_boxes`,
        i.e. gt_boxes[candidate_gt_indices[:, i]] = candidate_gt_boxes[:, i],
Hongkun Yu's avatar
Hongkun Yu committed
549
550
          where gt_boxes which is of shape [batch_size, MAX_INSTANCES, 4], M >=
          N, is the superset of candidate_gt_boxes.
Pengchong Jin's avatar
Pengchong Jin committed
551
552
553
554
555
556
557
558
559
560
561
      gt_masks: a tensor of [batch_size, MAX_INSTANCES, mask_height, mask_width]
        containing all the groundtruth masks which sample masks are drawn from.
        after sampling. The output masks are resized w.r.t the sampled RoIs.

    Returns:
      foreground_rois: a tensor of shape of [batch_size, K, 4] storing the RoI
        that corresponds to the sampled foreground masks, where
        K = num_mask_samples_per_image.
      foreground_classes: a tensor of shape of [batch_size, K] storing the
        classes corresponding to the sampled foreground masks.
      cropoped_foreground_masks: a tensor of shape of
Pengchong Jin's avatar
Pengchong Jin committed
562
        [batch_size, K, mask_target_size, mask_target_size] storing the
Pengchong Jin's avatar
Pengchong Jin committed
563
564
565
        cropped foreground masks used for training.
    """
    foreground_rois, foreground_classes, cropped_foreground_masks = (
Hongkun Yu's avatar
Hongkun Yu committed
566
567
568
569
570
        sample_and_crop_foreground_masks(candidate_rois, candidate_gt_boxes,
                                         candidate_gt_classes,
                                         candidate_gt_indices, gt_masks,
                                         self._num_mask_samples_per_image,
                                         self._mask_target_size))
Pengchong Jin's avatar
Pengchong Jin committed
571
    return foreground_rois, foreground_classes, cropped_foreground_masks