model.py 117.4 KB
Newer Older
W
Waleed Abdulla 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
"""
Mask R-CNN
The main Mask R-CNN model implemenetation.

Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""

import os
import sys
import glob
import random
import math
import datetime
import itertools
import json
import re
import logging
from collections import OrderedDict
W
Waleed Abdulla 已提交
21
import multiprocessing
W
Waleed Abdulla 已提交
22
import numpy as np
23
import skimage.transform
W
Waleed Abdulla 已提交
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
import tensorflow as tf
import keras
import keras.backend as K
import keras.layers as KL
import keras.initializers as KI
import keras.engine as KE
import keras.models as KM

import utils

# Requires TensorFlow 1.3+ and Keras 2.0.8+.
from distutils.version import LooseVersion
assert LooseVersion(tf.__version__) >= LooseVersion("1.3")
assert LooseVersion(keras.__version__) >= LooseVersion('2.0.8')


############################################################
#  Utility Functions
############################################################

def log(text, array=None):
    """Prints a text message. And, optionally, if a Numpy array is provided it
    prints it's shape, min, and max values.
    """
    if array is not None:
        text = text.ljust(25)
50
        text += ("shape: {:20}  min: {:10.5f}  max: {:10.5f}  {}".format(
W
Waleed Abdulla 已提交
51 52
            str(array.shape),
            array.min() if array.size else "",
53 54
            array.max() if array.size else "",
            array.dtype))
W
Waleed Abdulla 已提交
55 56 57 58
    print(text)


class BatchNorm(KL.BatchNormalization):
59 60
    """Extends the Keras BatchNormalization class to allow a central place
    to make changes if needed.
W
Waleed Abdulla 已提交
61 62

    Batch normalization has a negative effect on training if batches are small
63 64
    so this layer is often frozen (via setting in Config class) and functions
    as linear layer.
W
Waleed Abdulla 已提交
65 66
    """
    def call(self, inputs, training=None):
67 68 69 70 71 72 73
        """
        Note about training values:
            None: Train BN layers. This is the normal mode
            False: Freeze BN layers. Good when batch size is small
            True: (don't use). Set layer in training mode even when inferencing
        """
        return super(self.__class__, self).call(inputs, training=training)
W
Waleed Abdulla 已提交
74 75


76 77 78 79 80 81 82 83 84 85 86 87 88 89
def compute_backbone_shapes(config, image_shape):
    """Computes the width and height of each stage of the backbone network.
    
    Returns:
        [N, (height, width)]. Where N is the number of stages
    """
    # Currently supports ResNet only
    assert config.BACKBONE in ["resnet50", "resnet101"]
    return np.array(
        [[int(math.ceil(image_shape[0] / stride)),
            int(math.ceil(image_shape[1] / stride))]
            for stride in config.BACKBONE_STRIDES])


W
Waleed Abdulla 已提交
90 91 92 93 94 95 96 97
############################################################
#  Resnet Graph
############################################################

# Code adopted from:
# https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py

def identity_block(input_tensor, kernel_size, filters, stage, block,
98
                   use_bias=True, train_bn=True):
W
Waleed Abdulla 已提交
99 100 101 102 103 104 105
    """The identity_block is the block that has no conv layer at shortcut
    # Arguments
        input_tensor: input tensor
        kernel_size: defualt 3, the kernel size of middle conv layer at main path
        filters: list of integers, the nb_filters of 3 conv layer at main path
        stage: integer, current stage label, used for generating layer names
        block: 'a','b'..., current block label, used for generating layer names
106 107
        use_bias: Boolean. To use or not use a bias in conv layers.
        train_bn: Boolean. Train or freeze Batch Norm layres
W
Waleed Abdulla 已提交
108 109 110 111 112 113 114
    """
    nb_filter1, nb_filter2, nb_filter3 = filters
    conv_name_base = 'res' + str(stage) + block + '_branch'
    bn_name_base = 'bn' + str(stage) + block + '_branch'

    x = KL.Conv2D(nb_filter1, (1, 1), name=conv_name_base + '2a',
                  use_bias=use_bias)(input_tensor)
115
    x = BatchNorm(name=bn_name_base + '2a')(x, training=train_bn)
W
Waleed Abdulla 已提交
116 117 118 119
    x = KL.Activation('relu')(x)

    x = KL.Conv2D(nb_filter2, (kernel_size, kernel_size), padding='same',
                  name=conv_name_base + '2b', use_bias=use_bias)(x)
120
    x = BatchNorm(name=bn_name_base + '2b')(x, training=train_bn)
W
Waleed Abdulla 已提交
121 122 123 124
    x = KL.Activation('relu')(x)

    x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base + '2c',
                  use_bias=use_bias)(x)
125
    x = BatchNorm(name=bn_name_base + '2c')(x, training=train_bn)
W
Waleed Abdulla 已提交
126 127

    x = KL.Add()([x, input_tensor])
G
Gyuri Im 已提交
128
    x = KL.Activation('relu', name='res' + str(stage) + block + '_out')(x)
W
Waleed Abdulla 已提交
129 130 131
    return x


G
Gyuri Im 已提交
132
def conv_block(input_tensor, kernel_size, filters, stage, block,
133
               strides=(2, 2), use_bias=True, train_bn=True):
W
Waleed Abdulla 已提交
134 135 136 137 138 139 140
    """conv_block is the block that has a conv layer at shortcut
    # Arguments
        input_tensor: input tensor
        kernel_size: defualt 3, the kernel size of middle conv layer at main path
        filters: list of integers, the nb_filters of 3 conv layer at main path
        stage: integer, current stage label, used for generating layer names
        block: 'a','b'..., current block label, used for generating layer names
141 142
        use_bias: Boolean. To use or not use a bias in conv layers.
        train_bn: Boolean. Train or freeze Batch Norm layres
W
Waleed Abdulla 已提交
143 144 145 146 147 148 149 150 151
    Note that from stage 3, the first conv layer at main path is with subsample=(2,2)
    And the shortcut should have subsample=(2,2) as well
    """
    nb_filter1, nb_filter2, nb_filter3 = filters
    conv_name_base = 'res' + str(stage) + block + '_branch'
    bn_name_base = 'bn' + str(stage) + block + '_branch'

    x = KL.Conv2D(nb_filter1, (1, 1), strides=strides,
                  name=conv_name_base + '2a', use_bias=use_bias)(input_tensor)
152
    x = BatchNorm(name=bn_name_base + '2a')(x, training=train_bn)
W
Waleed Abdulla 已提交
153 154 155 156
    x = KL.Activation('relu')(x)

    x = KL.Conv2D(nb_filter2, (kernel_size, kernel_size), padding='same',
                  name=conv_name_base + '2b', use_bias=use_bias)(x)
157
    x = BatchNorm(name=bn_name_base + '2b')(x, training=train_bn)
W
Waleed Abdulla 已提交
158 159
    x = KL.Activation('relu')(x)

G
Gyuri Im 已提交
160 161
    x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base +
                  '2c', use_bias=use_bias)(x)
162
    x = BatchNorm(name=bn_name_base + '2c')(x, training=train_bn)
W
Waleed Abdulla 已提交
163 164 165

    shortcut = KL.Conv2D(nb_filter3, (1, 1), strides=strides,
                         name=conv_name_base + '1', use_bias=use_bias)(input_tensor)
166
    shortcut = BatchNorm(name=bn_name_base + '1')(shortcut, training=train_bn)
W
Waleed Abdulla 已提交
167 168

    x = KL.Add()([x, shortcut])
G
Gyuri Im 已提交
169
    x = KL.Activation('relu', name='res' + str(stage) + block + '_out')(x)
W
Waleed Abdulla 已提交
170 171 172
    return x


173 174 175 176 177 178
def resnet_graph(input_image, architecture, stage5=False, train_bn=True):
    """Build a ResNet graph.
        architecture: Can be resnet50 or resnet101
        stage5: Boolean. If False, stage5 of the network is not created
        train_bn: Boolean. Train or freeze Batch Norm layres
    """
W
Waleed Abdulla 已提交
179 180 181 182
    assert architecture in ["resnet50", "resnet101"]
    # Stage 1
    x = KL.ZeroPadding2D((3, 3))(input_image)
    x = KL.Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=True)(x)
183
    x = BatchNorm(name='bn_conv1')(x, training=train_bn)
W
Waleed Abdulla 已提交
184 185 186
    x = KL.Activation('relu')(x)
    C1 = x = KL.MaxPooling2D((3, 3), strides=(2, 2), padding="same")(x)
    # Stage 2
187 188 189
    x = conv_block(x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), train_bn=train_bn)
    x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', train_bn=train_bn)
    C2 = x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', train_bn=train_bn)
W
Waleed Abdulla 已提交
190
    # Stage 3
191 192 193 194
    x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', train_bn=train_bn)
    x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', train_bn=train_bn)
    x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', train_bn=train_bn)
    C3 = x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', train_bn=train_bn)
W
Waleed Abdulla 已提交
195
    # Stage 4
196
    x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', train_bn=train_bn)
W
Waleed Abdulla 已提交
197 198
    block_count = {"resnet50": 5, "resnet101": 22}[architecture]
    for i in range(block_count):
199
        x = identity_block(x, 3, [256, 256, 1024], stage=4, block=chr(98 + i), train_bn=train_bn)
W
Waleed Abdulla 已提交
200 201 202
    C4 = x
    # Stage 5
    if stage5:
203 204 205
        x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', train_bn=train_bn)
        x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', train_bn=train_bn)
        C5 = x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', train_bn=train_bn)
W
Waleed Abdulla 已提交
206 207 208 209 210 211 212 213 214 215 216
    else:
        C5 = None
    return [C1, C2, C3, C4, C5]


############################################################
#  Proposal Layer
############################################################

def apply_box_deltas_graph(boxes, deltas):
    """Applies the given deltas to the given boxes.
217 218
    boxes: [N, (y1, x1, y2, x2)] boxes to update
    deltas: [N, (dy, dx, log(dh), log(dw))] refinements to apply
W
Waleed Abdulla 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    """
    # Convert to y, x, h, w
    height = boxes[:, 2] - boxes[:, 0]
    width = boxes[:, 3] - boxes[:, 1]
    center_y = boxes[:, 0] + 0.5 * height
    center_x = boxes[:, 1] + 0.5 * width
    # Apply deltas
    center_y += deltas[:, 0] * height
    center_x += deltas[:, 1] * width
    height *= tf.exp(deltas[:, 2])
    width *= tf.exp(deltas[:, 3])
    # Convert back to y1, x1, y2, x2
    y1 = center_y - 0.5 * height
    x1 = center_x - 0.5 * width
    y2 = y1 + height
    x2 = x1 + width
    result = tf.stack([y1, x1, y2, x2], axis=1, name="apply_box_deltas_out")
    return result


def clip_boxes_graph(boxes, window):
    """
241
    boxes: [N, (y1, x1, y2, x2)]
W
Waleed Abdulla 已提交
242 243
    window: [4] in the form y1, x1, y2, x2
    """
244
    # Split
W
Waleed Abdulla 已提交
245 246 247 248 249 250 251 252
    wy1, wx1, wy2, wx2 = tf.split(window, 4)
    y1, x1, y2, x2 = tf.split(boxes, 4, axis=1)
    # Clip
    y1 = tf.maximum(tf.minimum(y1, wy2), wy1)
    x1 = tf.maximum(tf.minimum(x1, wx2), wx1)
    y2 = tf.maximum(tf.minimum(y2, wy2), wy1)
    x2 = tf.maximum(tf.minimum(x2, wx2), wx1)
    clipped = tf.concat([y1, x1, y2, x2], axis=1, name="clipped_boxes")
253
    clipped.set_shape((clipped.shape[0], 4))
W
Waleed Abdulla 已提交
254 255 256 257 258 259 260
    return clipped


class ProposalLayer(KE.Layer):
    """Receives anchor scores and selects a subset to pass as proposals
    to the second stage. Filtering is done based on anchor scores and
    non-max suppression to remove overlaps. It also applies bounding
W
Waleed Abdulla 已提交
261
    box refinement deltas to anchors.
W
Waleed Abdulla 已提交
262 263 264 265

    Inputs:
        rpn_probs: [batch, anchors, (bg prob, fg prob)]
        rpn_bbox: [batch, anchors, (dy, dx, log(dh), log(dw))]
266
        anchors: [batch, (y1, x1, y2, x2)] anchors in normalized coordinates
W
Waleed Abdulla 已提交
267 268 269 270

    Returns:
        Proposals in normalized coordinates [batch, rois, (y1, x1, y2, x2)]
    """
G
Gyuri Im 已提交
271

272
    def __init__(self, proposal_count, nms_threshold, config=None, **kwargs):
W
Waleed Abdulla 已提交
273 274 275 276 277 278 279 280 281 282 283
        super(ProposalLayer, self).__init__(**kwargs)
        self.config = config
        self.proposal_count = proposal_count
        self.nms_threshold = nms_threshold

    def call(self, inputs):
        # Box Scores. Use the foreground class confidence. [Batch, num_rois, 1]
        scores = inputs[0][:, :, 1]
        # Box deltas [batch, num_rois, 4]
        deltas = inputs[1]
        deltas = deltas * np.reshape(self.config.RPN_BBOX_STD_DEV, [1, 1, 4])
284 285
        # Anchors
        anchors = inputs[2]
W
Waleed Abdulla 已提交
286 287 288

        # Improve performance by trimming to top anchors by score
        # and doing the rest on the smaller subset.
289
        pre_nms_limit = tf.minimum(6000, tf.shape(anchors)[1])
G
Gyuri Im 已提交
290 291
        ix = tf.nn.top_k(scores, pre_nms_limit, sorted=True,
                         name="top_anchors").indices
W
Waleed Abdulla 已提交
292
        scores = utils.batch_slice([scores, ix], lambda x, y: tf.gather(x, y),
G
Gyuri Im 已提交
293
                                   self.config.IMAGES_PER_GPU)
W
Waleed Abdulla 已提交
294
        deltas = utils.batch_slice([deltas, ix], lambda x, y: tf.gather(x, y),
G
Gyuri Im 已提交
295
                                   self.config.IMAGES_PER_GPU)
296
        pre_nms_anchors = utils.batch_slice([anchors, ix], lambda a, x: tf.gather(a, x),
G
Gyuri Im 已提交
297 298
                                    self.config.IMAGES_PER_GPU,
                                    names=["pre_nms_anchors"])
W
Waleed Abdulla 已提交
299 300 301

        # Apply deltas to anchors to get refined anchors.
        # [batch, N, (y1, x1, y2, x2)]
302
        boxes = utils.batch_slice([pre_nms_anchors, deltas],
G
Gyuri Im 已提交
303 304 305
                                  lambda x, y: apply_box_deltas_graph(x, y),
                                  self.config.IMAGES_PER_GPU,
                                  names=["refined_anchors"])
W
Waleed Abdulla 已提交
306

307 308 309
        # Clip to image boundaries. Since we're in normalized coordinates,
        # clip to 0..1 range. [batch, N, (y1, x1, y2, x2)]
        window = np.array([0, 0, 1, 1], dtype=np.float32)
W
Waleed Abdulla 已提交
310
        boxes = utils.batch_slice(boxes,
G
Gyuri Im 已提交
311 312 313
                                  lambda x: clip_boxes_graph(x, window),
                                  self.config.IMAGES_PER_GPU,
                                  names=["refined_anchors_clipped"])
W
Waleed Abdulla 已提交
314 315 316 317 318 319

        # Filter out small boxes
        # According to Xinlei Chen's paper, this reduces detection accuracy
        # for small objects, so we're skipping it.

        # Non-max suppression
320
        def nms(boxes, scores):
W
Waleed Abdulla 已提交
321
            indices = tf.image.non_max_suppression(
322
                boxes, scores, self.proposal_count,
W
Waleed Abdulla 已提交
323
                self.nms_threshold, name="rpn_non_max_suppression")
324
            proposals = tf.gather(boxes, indices)
W
Waleed Abdulla 已提交
325
            # Pad if needed
W
Waleed Abdulla 已提交
326 327
            padding = tf.maximum(self.proposal_count - tf.shape(proposals)[0], 0)
            proposals = tf.pad(proposals, [(0, padding), (0, 0)])
W
Waleed Abdulla 已提交
328
            return proposals
329
        proposals = utils.batch_slice([boxes, scores], nms,
G
Gyuri Im 已提交
330
                                      self.config.IMAGES_PER_GPU)
W
Waleed Abdulla 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        return proposals

    def compute_output_shape(self, input_shape):
        return (None, self.proposal_count, 4)


############################################################
#  ROIAlign Layer
############################################################

def log2_graph(x):
    """Implementatin of Log2. TF doesn't have a native implemenation."""
    return tf.log(x) / tf.log(2.0)


class PyramidROIAlign(KE.Layer):
    """Implements ROI Pooling on multiple levels of the feature pyramid.

    Params:
    - pool_shape: [height, width] of the output pooled regions. Usually [7, 7]

    Inputs:
    - boxes: [batch, num_boxes, (y1, x1, y2, x2)] in normalized
             coordinates. Possibly padded with zeros if not enough
             boxes to fill the array.
356
    - image_meta: [batch, (meta data)] Image details. See compose_image_meta()
W
Waleed Abdulla 已提交
357 358 359 360 361 362 363 364
    - Feature maps: List of feature maps from different levels of the pyramid.
                    Each is [batch, height, width, channels]

    Output:
    Pooled regions in the shape: [batch, num_boxes, height, width, channels].
    The width and height are those specific in the pool_shape in the layer
    constructor.
    """
G
Gyuri Im 已提交
365

366
    def __init__(self, pool_shape, **kwargs):
W
Waleed Abdulla 已提交
367 368 369 370 371 372 373
        super(PyramidROIAlign, self).__init__(**kwargs)
        self.pool_shape = tuple(pool_shape)

    def call(self, inputs):
        # Crop boxes [batch, num_boxes, (y1, x1, y2, x2)] in normalized coords
        boxes = inputs[0]

374 375 376 377
        # Image meta
        # Holds details about the image. See compose_image_meta()
        image_meta = inputs[1]

W
Waleed Abdulla 已提交
378 379
        # Feature Maps. List of feature maps from different level of the
        # feature pyramid. Each is [batch, height, width, channels]
380
        feature_maps = inputs[2:]
W
Waleed Abdulla 已提交
381 382 383 384 385

        # Assign each ROI to a level in the pyramid based on the ROI area.
        y1, x1, y2, x2 = tf.split(boxes, 4, axis=2)
        h = y2 - y1
        w = x2 - x1
386 387
        # Use shape of first image. Images in a batch must have the same size.
        image_shape = parse_image_meta_graph(image_meta)['image_shape'][0]
W
Waleed Abdulla 已提交
388 389 390
        # Equation 1 in the Feature Pyramid Networks paper. Account for
        # the fact that our coordinates are normalized here.
        # e.g. a 224x224 ROI (in pixels) maps to P4
391
        image_area = tf.cast(image_shape[0] * image_shape[1], tf.float32)
G
Gyuri Im 已提交
392 393 394
        roi_level = log2_graph(tf.sqrt(h * w) / (224.0 / tf.sqrt(image_area)))
        roi_level = tf.minimum(5, tf.maximum(
            2, 4 + tf.cast(tf.round(roi_level), tf.int32)))
W
Waleed Abdulla 已提交
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
        roi_level = tf.squeeze(roi_level, 2)

        # Loop through levels and apply ROI pooling to each. P2 to P5.
        pooled = []
        box_to_level = []
        for i, level in enumerate(range(2, 6)):
            ix = tf.where(tf.equal(roi_level, level))
            level_boxes = tf.gather_nd(boxes, ix)

            # Box indicies for crop_and_resize.
            box_indices = tf.cast(ix[:, 0], tf.int32)

            # Keep track of which box is mapped to which level
            box_to_level.append(ix)

            # Stop gradient propogation to ROI proposals
            level_boxes = tf.stop_gradient(level_boxes)
            box_indices = tf.stop_gradient(box_indices)

            # Crop and Resize
            # From Mask R-CNN paper: "We sample four regular locations, so
            # that we can evaluate either max or average pooling. In fact,
            # interpolating only a single value at each bin center (without
            # pooling) is nearly as effective."
            #
            # Here we use the simplified approach of a single value per bin,
            # which is how it's done in tf.crop_and_resize()
            # Result: [batch * num_boxes, pool_height, pool_width, channels]
            pooled.append(tf.image.crop_and_resize(
                feature_maps[i], level_boxes, box_indices, self.pool_shape,
                method="bilinear"))

        # Pack pooled features into one tensor
        pooled = tf.concat(pooled, axis=0)

        # Pack box_to_level mapping into one array and add another
        # column representing the order of pooled boxes
        box_to_level = tf.concat(box_to_level, axis=0)
        box_range = tf.expand_dims(tf.range(tf.shape(box_to_level)[0]), 1)
        box_to_level = tf.concat([tf.cast(box_to_level, tf.int32), box_range],
                                 axis=1)

        # Rearrange pooled features to match the order of the original boxes
        # Sort box_to_level by batch then box index
        # TF doesn't have a way to sort by two columns, so merge them and sort.
        sorting_tensor = box_to_level[:, 0] * 100000 + box_to_level[:, 1]
G
Gyuri Im 已提交
441 442 443
        ix = tf.nn.top_k(sorting_tensor, k=tf.shape(
            box_to_level)[0]).indices[::-1]
        ix = tf.gather(box_to_level[:, 2], ix)
W
Waleed Abdulla 已提交
444 445 446 447 448 449 450
        pooled = tf.gather(pooled, ix)

        # Re-add the batch dimension
        pooled = tf.expand_dims(pooled, 0)
        return pooled

    def compute_output_shape(self, input_shape):
451
        return input_shape[0][:2] + self.pool_shape + (input_shape[2][-1], )
W
Waleed Abdulla 已提交
452 453 454 455 456 457


############################################################
#  Detection Target Layer
############################################################

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
def overlaps_graph(boxes1, boxes2):
    """Computes IoU overlaps between two sets of boxes.
    boxes1, boxes2: [N, (y1, x1, y2, x2)].
    """
    # 1. Tile boxes2 and repeate boxes1. This allows us to compare
    # every boxes1 against every boxes2 without loops.
    # TF doesn't have an equivalent to np.repeate() so simulate it
    # using tf.tile() and tf.reshape.
    b1 = tf.reshape(tf.tile(tf.expand_dims(boxes1, 1),
                            [1, 1, tf.shape(boxes2)[0]]), [-1, 4])
    b2 = tf.tile(boxes2, [tf.shape(boxes1)[0], 1])
    # 2. Compute intersections
    b1_y1, b1_x1, b1_y2, b1_x2 = tf.split(b1, 4, axis=1)
    b2_y1, b2_x1, b2_y2, b2_x2 = tf.split(b2, 4, axis=1)
    y1 = tf.maximum(b1_y1, b2_y1)
    x1 = tf.maximum(b1_x1, b2_x1)
    y2 = tf.minimum(b1_y2, b2_y2)
    x2 = tf.minimum(b1_x2, b2_x2)
    intersection = tf.maximum(x2 - x1, 0) * tf.maximum(y2 - y1, 0)
    # 3. Compute unions
    b1_area = (b1_y2 - b1_y1) * (b1_x2 - b1_x1)
    b2_area = (b2_y2 - b2_y1) * (b2_x2 - b2_x1)
    union = b1_area + b2_area - intersection
    # 4. Compute IoU and reshape to [boxes1, boxes2]
    iou = intersection / union
    overlaps = tf.reshape(iou, [tf.shape(boxes1)[0], tf.shape(boxes2)[0]])
    return overlaps


487
def detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config):
W
Waleed Abdulla 已提交
488 489 490 491 492 493
    """Generates detection targets for one image. Subsamples proposals and
    generates target class IDs, bounding box deltas, and masks for each.

    Inputs:
    proposals: [N, (y1, x1, y2, x2)] in normalized coordinates. Might
               be zero padded if there are not enough proposals.
494 495
    gt_class_ids: [MAX_GT_INSTANCES] int class IDs
    gt_boxes: [MAX_GT_INSTANCES, (y1, x1, y2, x2)] in normalized coordinates.
W
Waleed Abdulla 已提交
496 497 498 499 500 501 502
    gt_masks: [height, width, MAX_GT_INSTANCES] of boolean type.

    Returns: Target ROIs and corresponding class IDs, bounding box shifts,
    and masks.
    rois: [TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)] in normalized coordinates
    class_ids: [TRAIN_ROIS_PER_IMAGE]. Integer class IDs. Zero padded.
    deltas: [TRAIN_ROIS_PER_IMAGE, NUM_CLASSES, (dy, dx, log(dh), log(dw))]
W
Waleed Abdulla 已提交
503
            Class-specific bbox refinements.
W
Waleed Abdulla 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516
    masks: [TRAIN_ROIS_PER_IMAGE, height, width). Masks cropped to bbox
           boundaries and resized to neural network output size.

    Note: Returned arrays might be zero padded if not enough target ROIs.
    """
    # Assertions
    asserts = [
        tf.Assert(tf.greater(tf.shape(proposals)[0], 0), [proposals],
                  name="roi_assertion"),
    ]
    with tf.control_dependencies(asserts):
        proposals = tf.identity(proposals)

W
Waleed Abdulla 已提交
517 518 519
    # Remove zero padding
    proposals, _ = trim_zeros_graph(proposals, name="trim_proposals")
    gt_boxes, non_zeros = trim_zeros_graph(gt_boxes, name="trim_gt_boxes")
520 521
    gt_class_ids = tf.boolean_mask(gt_class_ids, non_zeros,
                                   name="trim_gt_class_ids")
W
Waleed Abdulla 已提交
522 523
    gt_masks = tf.gather(gt_masks, tf.where(non_zeros)[:, 0], axis=2,
                         name="trim_gt_masks")
W
Waleed Abdulla 已提交
524

W
Waleed Abdulla 已提交
525 526 527 528 529 530 531 532 533 534 535
    # Handle COCO crowds
    # A crowd box in COCO is a bounding box around several instances. Exclude
    # them from training. A crowd box is given a negative class ID.
    crowd_ix = tf.where(gt_class_ids < 0)[:, 0]
    non_crowd_ix = tf.where(gt_class_ids > 0)[:, 0]
    crowd_boxes = tf.gather(gt_boxes, crowd_ix)
    crowd_masks = tf.gather(gt_masks, crowd_ix, axis=2)
    gt_class_ids = tf.gather(gt_class_ids, non_crowd_ix)
    gt_boxes = tf.gather(gt_boxes, non_crowd_ix)
    gt_masks = tf.gather(gt_masks, non_crowd_ix, axis=2)

W
Waleed Abdulla 已提交
536
    # Compute overlaps matrix [proposals, gt_boxes]
537
    overlaps = overlaps_graph(proposals, gt_boxes)
W
Waleed Abdulla 已提交
538

W
Waleed Abdulla 已提交
539 540 541 542 543
    # Compute overlaps with crowd boxes [anchors, crowds]
    crowd_overlaps = overlaps_graph(proposals, crowd_boxes)
    crowd_iou_max = tf.reduce_max(crowd_overlaps, axis=1)
    no_crowd_bool = (crowd_iou_max < 0.001)

W
Waleed Abdulla 已提交
544 545 546 547 548
    # Determine postive and negative ROIs
    roi_iou_max = tf.reduce_max(overlaps, axis=1)
    # 1. Positive ROIs are those with >= 0.5 IoU with a GT box
    positive_roi_bool = (roi_iou_max >= 0.5)
    positive_indices = tf.where(positive_roi_bool)[:, 0]
W
Waleed Abdulla 已提交
549 550
    # 2. Negative ROIs are those with < 0.5 with every GT box. Skip crowds.
    negative_indices = tf.where(tf.logical_and(roi_iou_max < 0.5, no_crowd_bool))[:, 0]
W
Waleed Abdulla 已提交
551 552 553

    # Subsample ROIs. Aim for 33% positive
    # Positive ROIs
G
Gyuri Im 已提交
554 555
    positive_count = int(config.TRAIN_ROIS_PER_IMAGE *
                         config.ROI_POSITIVE_RATIO)
W
Waleed Abdulla 已提交
556
    positive_indices = tf.random_shuffle(positive_indices)[:positive_count]
W
Waleed Abdulla 已提交
557 558
    positive_count = tf.shape(positive_indices)[0]
    # Negative ROIs. Add enough to maintain positive:negative ratio.
559 560
    r = 1.0 / config.ROI_POSITIVE_RATIO
    negative_count = tf.cast(r * tf.cast(positive_count, tf.float32), tf.int32) - positive_count
W
Waleed Abdulla 已提交
561 562 563 564 565 566 567 568 569
    negative_indices = tf.random_shuffle(negative_indices)[:negative_count]
    # Gather selected ROIs
    positive_rois = tf.gather(proposals, positive_indices)
    negative_rois = tf.gather(proposals, negative_indices)

    # Assign positive ROIs to GT boxes.
    positive_overlaps = tf.gather(overlaps, positive_indices)
    roi_gt_box_assignment = tf.argmax(positive_overlaps, axis=1)
    roi_gt_boxes = tf.gather(gt_boxes, roi_gt_box_assignment)
570
    roi_gt_class_ids = tf.gather(gt_class_ids, roi_gt_box_assignment)
W
Waleed Abdulla 已提交
571 572

    # Compute bbox refinement for positive ROIs
573
    deltas = utils.box_refinement_graph(positive_rois, roi_gt_boxes)
W
Waleed Abdulla 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587
    deltas /= config.BBOX_STD_DEV

    # Assign positive ROIs to GT masks
    # Permute masks to [N, height, width, 1]
    transposed_masks = tf.expand_dims(tf.transpose(gt_masks, [2, 0, 1]), -1)
    # Pick the right mask for each ROI
    roi_masks = tf.gather(transposed_masks, roi_gt_box_assignment)

    # Compute mask targets
    boxes = positive_rois
    if config.USE_MINI_MASK:
        # Transform ROI corrdinates from normalized image space
        # to normalized mini-mask space.
        y1, x1, y2, x2 = tf.split(positive_rois, 4, axis=1)
588
        gt_y1, gt_x1, gt_y2, gt_x2 = tf.split(roi_gt_boxes, 4, axis=1)
W
Waleed Abdulla 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
        gt_h = gt_y2 - gt_y1
        gt_w = gt_x2 - gt_x1
        y1 = (y1 - gt_y1) / gt_h
        x1 = (x1 - gt_x1) / gt_w
        y2 = (y2 - gt_y1) / gt_h
        x2 = (x2 - gt_x1) / gt_w
        boxes = tf.concat([y1, x1, y2, x2], 1)
    box_ids = tf.range(0, tf.shape(roi_masks)[0])
    masks = tf.image.crop_and_resize(tf.cast(roi_masks, tf.float32), boxes,
                                     box_ids,
                                     config.MASK_SHAPE)
    # Remove the extra dimension from masks.
    masks = tf.squeeze(masks, axis=3)

    # Threshold mask pixels at 0.5 to have GT masks be 0 or 1 to use with
    # binary cross entropy loss.
    masks = tf.round(masks)

    # Append negative ROIs and pad bbox deltas and masks that
    # are not used for negative ROIs with zeros.
    rois = tf.concat([positive_rois, negative_rois], axis=0)
    N = tf.shape(negative_rois)[0]
    P = tf.maximum(config.TRAIN_ROIS_PER_IMAGE - tf.shape(rois)[0], 0)
    rois = tf.pad(rois, [(0, P), (0, 0)])
G
Gyuri Im 已提交
613 614 615 616
    roi_gt_boxes = tf.pad(roi_gt_boxes, [(0, N + P), (0, 0)])
    roi_gt_class_ids = tf.pad(roi_gt_class_ids, [(0, N + P)])
    deltas = tf.pad(deltas, [(0, N + P), (0, 0)])
    masks = tf.pad(masks, [[0, N + P], (0, 0), (0, 0)])
W
Waleed Abdulla 已提交
617

618
    return rois, roi_gt_class_ids, deltas, masks
W
Waleed Abdulla 已提交
619 620 621


class DetectionTargetLayer(KE.Layer):
W
Waleed Abdulla 已提交
622
    """Subsamples proposals and generates target box refinement, class_ids,
W
Waleed Abdulla 已提交
623 624 625 626 627
    and masks for each.

    Inputs:
    proposals: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might
               be zero padded if there are not enough proposals.
628 629 630
    gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class IDs.
    gt_boxes: [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)] in normalized
              coordinates.
W
Waleed Abdulla 已提交
631 632 633 634 635 636 637
    gt_masks: [batch, height, width, MAX_GT_INSTANCES] of boolean type

    Returns: Target ROIs and corresponding class IDs, bounding box shifts,
    and masks.
    rois: [batch, TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)] in normalized
          coordinates
    target_class_ids: [batch, TRAIN_ROIS_PER_IMAGE]. Integer class IDs.
G
Gyuri Im 已提交
638
    target_deltas: [batch, TRAIN_ROIS_PER_IMAGE, NUM_CLASSES,
W
Waleed Abdulla 已提交
639
                    (dy, dx, log(dh), log(dw), class_id)]
W
Waleed Abdulla 已提交
640
                   Class-specific bbox refinements.
W
Waleed Abdulla 已提交
641 642 643 644 645 646
    target_mask: [batch, TRAIN_ROIS_PER_IMAGE, height, width)
                 Masks cropped to bbox boundaries and resized to neural
                 network output size.

    Note: Returned arrays might be zero padded if not enough target ROIs.
    """
G
Gyuri Im 已提交
647

W
Waleed Abdulla 已提交
648 649 650 651 652 653
    def __init__(self, config, **kwargs):
        super(DetectionTargetLayer, self).__init__(**kwargs)
        self.config = config

    def call(self, inputs):
        proposals = inputs[0]
654 655 656
        gt_class_ids = inputs[1]
        gt_boxes = inputs[2]
        gt_masks = inputs[3]
W
Waleed Abdulla 已提交
657 658 659 660 661

        # Slice the batch and run a graph for each slice
        # TODO: Rename target_bbox to target_deltas for clarity
        names = ["rois", "target_class_ids", "target_bbox", "target_mask"]
        outputs = utils.batch_slice(
662
            [proposals, gt_class_ids, gt_boxes, gt_masks],
G
Gyuri Im 已提交
663 664
            lambda w, x, y, z: detection_targets_graph(
                w, x, y, z, self.config),
W
Waleed Abdulla 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
            self.config.IMAGES_PER_GPU, names=names)
        return outputs

    def compute_output_shape(self, input_shape):
        return [
            (None, self.config.TRAIN_ROIS_PER_IMAGE, 4),  # rois
            (None, 1),  # class_ids
            (None, self.config.TRAIN_ROIS_PER_IMAGE, 4),  # deltas
            (None, self.config.TRAIN_ROIS_PER_IMAGE, self.config.MASK_SHAPE[0],
             self.config.MASK_SHAPE[1])  # masks
        ]

    def compute_mask(self, inputs, mask=None):
        return [None, None, None, None]


############################################################
#  Detection Layer
############################################################

685 686 687 688 689 690 691 692 693 694 695 696
def refine_detections_graph(rois, probs, deltas, window, config):
    """Refine classified proposals and filter overlaps and return final
    detections.

    Inputs:
        rois: [N, (y1, x1, y2, x2)] in normalized coordinates
        probs: [N, num_classes]. Class probabilities.
        deltas: [N, num_classes, (dy, dx, log(dh), log(dw))]. Class-specific
                bounding box deltas.
        window: (y1, x1, y2, x2) in image coordinates. The part of the image
            that contains the image excluding the padding.

697
    Returns detections shaped: [N, (y1, x1, y2, x2, class_id, score)] where
698
        coordinates are normalized.
699 700 701 702
    """
    # Class IDs per ROI
    class_ids = tf.argmax(probs, axis=1, output_type=tf.int32)
    # Class probability of the top class of each ROI
703 704
    indices = tf.stack([tf.range(probs.shape[0]), class_ids], axis=1)
    class_scores = tf.gather_nd(probs, indices)
705
    # Class-specific bounding box deltas
706
    deltas_specific = tf.gather_nd(deltas, indices)
707 708 709 710 711 712
    # Apply bounding box deltas
    # Shape: [boxes, (y1, x1, y2, x2)] in normalized coordinates
    refined_rois = apply_box_deltas_graph(
        rois, deltas_specific * config.BBOX_STD_DEV)
    # Clip boxes to image window
    refined_rois = clip_boxes_graph(refined_rois, window)
713

714 715 716
    # TODO: Filter out boxes with zero area

    # Filter out background boxes
717
    keep = tf.where(class_ids > 0)[:, 0]
718 719
    # Filter out low confidence boxes
    if config.DETECTION_MIN_CONFIDENCE:
720 721 722 723
        conf_keep = tf.where(class_scores >= config.DETECTION_MIN_CONFIDENCE)[:, 0]
        keep = tf.sets.set_intersection(tf.expand_dims(keep, 0),
                                        tf.expand_dims(conf_keep, 0))
        keep = tf.sparse_tensor_to_dense(keep)[0]
724 725

    # Apply per-class NMS
726
    # 1. Prepare variables
C
Cory Pruce 已提交
727 728 729
    pre_nms_class_ids = tf.gather(class_ids, keep)
    pre_nms_scores = tf.gather(class_scores, keep)
    pre_nms_rois = tf.gather(refined_rois,   keep)
730
    unique_pre_nms_class_ids = tf.unique(pre_nms_class_ids)[0]
731

732 733 734 735
    def nms_keep_map(class_id):
        """Apply Non-Maximum Suppression on ROIs of the given class."""
        # Indices of ROIs of the given class
        ixs = tf.where(tf.equal(pre_nms_class_ids, class_id))[:, 0]
736 737
        # Apply NMS
        class_keep = tf.image.non_max_suppression(
738
                tf.gather(pre_nms_rois, ixs),
739
                tf.gather(pre_nms_scores, ixs),
740
                max_output_size=config.DETECTION_MAX_INSTANCES,
741 742
                iou_threshold=config.DETECTION_NMS_THRESHOLD)
        # Map indicies
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
        class_keep = tf.gather(keep, tf.gather(ixs, class_keep))
        # Pad with -1 so returned tensors have the same shape
        gap = config.DETECTION_MAX_INSTANCES - tf.shape(class_keep)[0]
        class_keep = tf.pad(class_keep, [(0, gap)],
                            mode='CONSTANT', constant_values=-1)
        # Set shape so map_fn() can infer result shape
        class_keep.set_shape([config.DETECTION_MAX_INSTANCES])
        return class_keep

    # 2. Map over class IDs
    nms_keep = tf.map_fn(nms_keep_map, unique_pre_nms_class_ids,
                         dtype=tf.int64)
    # 3. Merge results into one list, and remove -1 padding
    nms_keep = tf.reshape(nms_keep, [-1])
    nms_keep = tf.gather(nms_keep, tf.where(nms_keep > -1)[:, 0])
    # 4. Compute intersection between keep and nms_keep
    keep = tf.sets.set_intersection(tf.expand_dims(keep, 0),
                                    tf.expand_dims(nms_keep, 0))
    keep = tf.sparse_tensor_to_dense(keep)[0]
762
    # Keep top detections
763
    roi_count = config.DETECTION_MAX_INSTANCES
764 765 766
    class_scores_keep = tf.gather(class_scores, keep)
    num_keep = tf.minimum(tf.shape(class_scores_keep)[0], roi_count)
    top_ids = tf.nn.top_k(class_scores_keep, k=num_keep, sorted=True)[1]
767
    keep = tf.gather(keep, top_ids)
S
Shenoy 已提交
768

769
    # Arrange output as [N, (y1, x1, y2, x2, class_id, score)]
770
    # Coordinates are normalized.
771
    detections = tf.concat([
772
        tf.gather(refined_rois, keep),
773 774 775
        tf.to_float(tf.gather(class_ids, keep))[..., tf.newaxis],
        tf.gather(class_scores, keep)[..., tf.newaxis]
        ], axis=1)
776 777

    # Pad with zeros if detections < DETECTION_MAX_INSTANCES
778 779 780
    gap = config.DETECTION_MAX_INSTANCES - tf.shape(detections)[0]
    detections = tf.pad(detections, [(0, gap), (0, 0)], "CONSTANT")
    return detections
781

W
Waleed Abdulla 已提交
782 783 784 785 786 787

class DetectionLayer(KE.Layer):
    """Takes classified proposal boxes and their bounding box deltas and
    returns the final detection boxes.

    Returns:
788
    [batch, num_detections, (y1, x1, y2, x2, class_id, class_score)] where
789
    coordinates are normalized.
W
Waleed Abdulla 已提交
790
    """
G
Gyuri Im 已提交
791

W
Waleed Abdulla 已提交
792 793 794 795 796
    def __init__(self, config=None, **kwargs):
        super(DetectionLayer, self).__init__(**kwargs)
        self.config = config

    def call(self, inputs):
797
        rois = inputs[0]
798
        mrcnn_class = inputs[1]
799 800
        mrcnn_bbox = inputs[2]
        image_meta = inputs[3]
801

802 803 804 805 806 807 808 809
        # Get windows of images in normalized coordinates. Windows are the area
        # in the image that excludes the padding.
        # Use the shape of the first image in the batch to normalize the window
        # because we know that all images get resized to the same size.
        m = parse_image_meta_graph(image_meta)
        image_shape = m['image_shape'][0]
        window = norm_boxes_graph(m['window'], image_shape[:2])
        
810
        # Run detection refinement graph on each item in the batch
811
        detections_batch = utils.batch_slice(
812 813 814
            [rois, mrcnn_class, mrcnn_bbox, window],
            lambda x, y, w, z: refine_detections_graph(x, y, w, z, self.config),
            self.config.IMAGES_PER_GPU)
815 816

        # Reshape output
817 818
        # [batch, num_detections, (y1, x1, y2, x2, class_score)] in
        # normalized coordinates
819
        return tf.reshape(
820 821
            detections_batch,
            [self.config.BATCH_SIZE, self.config.DETECTION_MAX_INSTANCES, 6])
822

W
Waleed Abdulla 已提交
823 824 825 826
    def compute_output_shape(self, input_shape):
        return (None, self.config.DETECTION_MAX_INSTANCES, 6)


W
Waleed Abdulla 已提交
827 828 829
############################################################
#  Region Proposal Network (RPN)
############################################################
W
Waleed Abdulla 已提交
830 831 832 833 834 835 836 837 838 839 840

def rpn_graph(feature_map, anchors_per_location, anchor_stride):
    """Builds the computation graph of Region Proposal Network.

    feature_map: backbone features [batch, height, width, depth]
    anchors_per_location: number of anchors per pixel in the feature map
    anchor_stride: Controls the density of anchors. Typically 1 (anchors for
                   every pixel in the feature map), or 2 (every other pixel).

    Returns:
        rpn_logits: [batch, H, W, 2] Anchor classifier logits (before softmax)
841
        rpn_probs: [batch, H, W, 2] Anchor classifier probabilities.
W
Waleed Abdulla 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
        rpn_bbox: [batch, H, W, (dy, dx, log(dh), log(dw))] Deltas to be
                  applied to anchors.
    """
    # TODO: check if stride of 2 causes alignment issues if the featuremap
    #       is not even.
    # Shared convolutional base of the RPN
    shared = KL.Conv2D(512, (3, 3), padding='same', activation='relu',
                       strides=anchor_stride,
                       name='rpn_conv_shared')(feature_map)

    # Anchor Score. [batch, height, width, anchors per location * 2].
    x = KL.Conv2D(2 * anchors_per_location, (1, 1), padding='valid',
                  activation='linear', name='rpn_class_raw')(shared)

    # Reshape to [batch, anchors, 2]
    rpn_class_logits = KL.Lambda(
        lambda t: tf.reshape(t, [tf.shape(t)[0], -1, 2]))(x)

    # Softmax on last dimension of BG/FG.
G
Gyuri Im 已提交
861 862
    rpn_probs = KL.Activation(
        "softmax", name="rpn_class_xxx")(rpn_class_logits)
W
Waleed Abdulla 已提交
863 864 865

    # Bounding box refinement. [batch, H, W, anchors per location, depth]
    # where depth is [x, y, log(w), log(h)]
G
Gyuri Im 已提交
866
    x = KL.Conv2D(anchors_per_location * 4, (1, 1), padding="valid",
W
Waleed Abdulla 已提交
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
                  activation='linear', name='rpn_bbox_pred')(shared)

    # Reshape to [batch, anchors, 4]
    rpn_bbox = KL.Lambda(lambda t: tf.reshape(t, [tf.shape(t)[0], -1, 4]))(x)

    return [rpn_class_logits, rpn_probs, rpn_bbox]


def build_rpn_model(anchor_stride, anchors_per_location, depth):
    """Builds a Keras model of the Region Proposal Network.
    It wraps the RPN graph so it can be used multiple times with shared
    weights.

    anchors_per_location: number of anchors per pixel in the feature map
    anchor_stride: Controls the density of anchors. Typically 1 (anchors for
                   every pixel in the feature map), or 2 (every other pixel).
    depth: Depth of the backbone feature map.

    Returns a Keras Model object. The model outputs, when called, are:
    rpn_logits: [batch, H, W, 2] Anchor classifier logits (before softmax)
    rpn_probs: [batch, W, W, 2] Anchor classifier probabilities.
    rpn_bbox: [batch, H, W, (dy, dx, log(dh), log(dw))] Deltas to be
                applied to anchors.
    """
    input_feature_map = KL.Input(shape=[None, None, depth],
                                 name="input_rpn_feature_map")
    outputs = rpn_graph(input_feature_map, anchors_per_location, anchor_stride)
    return KM.Model([input_feature_map], outputs, name="rpn_model")


############################################################
#  Feature Pyramid Network Heads
############################################################

901 902
def fpn_classifier_graph(rois, feature_maps, image_meta,
                         pool_size, num_classes, train_bn=True):
W
Waleed Abdulla 已提交
903 904 905 906 907 908 909
    """Builds the computation graph of the feature pyramid network classifier
    and regressor heads.

    rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
          coordinates.
    feature_maps: List of feature maps from diffent layers of the pyramid,
                  [P2, P3, P4, P5]. Each has a different resolution.
910
    - image_meta: [batch, (meta data)] Image details. See compose_image_meta()
W
Waleed Abdulla 已提交
911 912
    pool_size: The width of the square feature map generated from ROI Pooling.
    num_classes: number of classes, which determines the depth of the results
913
    train_bn: Boolean. Train or freeze Batch Norm layres
W
Waleed Abdulla 已提交
914 915 916 917

    Returns:
        logits: [N, NUM_CLASSES] classifier logits (before softmax)
        probs: [N, NUM_CLASSES] classifier probabilities
G
Gyuri Im 已提交
918
        bbox_deltas: [N, (dy, dx, log(dh), log(dw))] Deltas to apply to
W
Waleed Abdulla 已提交
919 920 921 922
                     proposal boxes
    """
    # ROI Pooling
    # Shape: [batch, num_boxes, pool_height, pool_width, channels]
923 924
    x = PyramidROIAlign([pool_size, pool_size],
                        name="roi_align_classifier")([rois, image_meta] + feature_maps)
W
Waleed Abdulla 已提交
925 926 927
    # Two 1024 FC layers (implemented with Conv2D for consistency)
    x = KL.TimeDistributed(KL.Conv2D(1024, (pool_size, pool_size), padding="valid"),
                           name="mrcnn_class_conv1")(x)
928
    x = KL.TimeDistributed(BatchNorm(), name='mrcnn_class_bn1')(x, training=train_bn)
W
Waleed Abdulla 已提交
929 930 931
    x = KL.Activation('relu')(x)
    x = KL.TimeDistributed(KL.Conv2D(1024, (1, 1)),
                           name="mrcnn_class_conv2")(x)
932
    x = KL.TimeDistributed(BatchNorm(), name='mrcnn_class_bn2')(x, training=train_bn)
W
Waleed Abdulla 已提交
933 934 935 936 937 938 939 940 941 942 943 944 945
    x = KL.Activation('relu')(x)

    shared = KL.Lambda(lambda x: K.squeeze(K.squeeze(x, 3), 2),
                       name="pool_squeeze")(x)

    # Classifier head
    mrcnn_class_logits = KL.TimeDistributed(KL.Dense(num_classes),
                                            name='mrcnn_class_logits')(shared)
    mrcnn_probs = KL.TimeDistributed(KL.Activation("softmax"),
                                     name="mrcnn_class")(mrcnn_class_logits)

    # BBox head
    # [batch, boxes, num_classes * (dy, dx, log(dh), log(dw))]
G
Gyuri Im 已提交
946
    x = KL.TimeDistributed(KL.Dense(num_classes * 4, activation='linear'),
W
Waleed Abdulla 已提交
947 948 949 950 951 952 953 954
                           name='mrcnn_bbox_fc')(shared)
    # Reshape to [batch, boxes, num_classes, (dy, dx, log(dh), log(dw))]
    s = K.int_shape(x)
    mrcnn_bbox = KL.Reshape((s[1], num_classes, 4), name="mrcnn_bbox")(x)

    return mrcnn_class_logits, mrcnn_probs, mrcnn_bbox


955
def build_fpn_mask_graph(rois, feature_maps, image_meta,
956
                         pool_size, num_classes, train_bn=True):
W
Waleed Abdulla 已提交
957 958 959 960 961 962
    """Builds the computation graph of the mask head of Feature Pyramid Network.

    rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
          coordinates.
    feature_maps: List of feature maps from diffent layers of the pyramid,
                  [P2, P3, P4, P5]. Each has a different resolution.
963
    image_meta: [batch, (meta data)] Image details. See compose_image_meta()
W
Waleed Abdulla 已提交
964 965
    pool_size: The width of the square feature map generated from ROI Pooling.
    num_classes: number of classes, which determines the depth of the results
966
    train_bn: Boolean. Train or freeze Batch Norm layres
W
Waleed Abdulla 已提交
967 968 969 970 971

    Returns: Masks [batch, roi_count, height, width, num_classes]
    """
    # ROI Pooling
    # Shape: [batch, boxes, pool_height, pool_width, channels]
972 973
    x = PyramidROIAlign([pool_size, pool_size],
                        name="roi_align_mask")([rois, image_meta] + feature_maps)
W
Waleed Abdulla 已提交
974 975 976 977

    # Conv layers
    x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding="same"),
                           name="mrcnn_mask_conv1")(x)
978 979
    x = KL.TimeDistributed(BatchNorm(),
                           name='mrcnn_mask_bn1')(x, training=train_bn)
W
Waleed Abdulla 已提交
980 981 982 983
    x = KL.Activation('relu')(x)

    x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding="same"),
                           name="mrcnn_mask_conv2")(x)
984 985
    x = KL.TimeDistributed(BatchNorm(),
                           name='mrcnn_mask_bn2')(x, training=train_bn)
W
Waleed Abdulla 已提交
986 987 988 989
    x = KL.Activation('relu')(x)

    x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding="same"),
                           name="mrcnn_mask_conv3")(x)
990 991
    x = KL.TimeDistributed(BatchNorm(),
                           name='mrcnn_mask_bn3')(x, training=train_bn)
W
Waleed Abdulla 已提交
992 993 994 995
    x = KL.Activation('relu')(x)

    x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding="same"),
                           name="mrcnn_mask_conv4")(x)
996 997
    x = KL.TimeDistributed(BatchNorm(),
                           name='mrcnn_mask_bn4')(x, training=train_bn)
W
Waleed Abdulla 已提交
998 999
    x = KL.Activation('relu')(x)

G
Gyuri Im 已提交
1000
    x = KL.TimeDistributed(KL.Conv2DTranspose(256, (2, 2), strides=2, activation="relu"),
W
Waleed Abdulla 已提交
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
                           name="mrcnn_mask_deconv")(x)
    x = KL.TimeDistributed(KL.Conv2D(num_classes, (1, 1), strides=1, activation="sigmoid"),
                           name="mrcnn_mask")(x)
    return x


############################################################
#  Loss Functions
############################################################

def smooth_l1_loss(y_true, y_pred):
    """Implements Smooth-L1 loss.
    y_true and y_pred are typicallly: [N, 4], but could be any shape.
    """
    diff = K.abs(y_true - y_pred)
    less_than_one = K.cast(K.less(diff, 1.0), "float32")
G
Gyuri Im 已提交
1017
    loss = (less_than_one * 0.5 * diff**2) + (1 - less_than_one) * (diff - 0.5)
W
Waleed Abdulla 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    return loss


def rpn_class_loss_graph(rpn_match, rpn_class_logits):
    """RPN anchor classifier loss.

    rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
               -1=negative, 0=neutral anchor.
    rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for FG/BG.
    """
    # Squeeze last dim to simplify
    rpn_match = tf.squeeze(rpn_match, -1)
    # Get anchor classes. Convert the -1/+1 match to 0/1 values.
    anchor_class = K.cast(K.equal(rpn_match, 1), tf.int32)
    # Positive and Negative anchors contribute to the loss,
    # but neutral anchors (match value = 0) don't.
    indices = tf.where(K.not_equal(rpn_match, 0))
    # Pick rows that contribute to the loss and filter out the rest.
    rpn_class_logits = tf.gather_nd(rpn_class_logits, indices)
    anchor_class = tf.gather_nd(anchor_class, indices)
    # Crossentropy loss
G
Gyuri Im 已提交
1039 1040
    loss = K.sparse_categorical_crossentropy(target=anchor_class,
                                             output=rpn_class_logits,
W
Waleed Abdulla 已提交
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
                                             from_logits=True)
    loss = K.switch(tf.size(loss) > 0, K.mean(loss), tf.constant(0.0))
    return loss


def rpn_bbox_loss_graph(config, target_bbox, rpn_match, rpn_bbox):
    """Return the RPN bounding box loss graph.

    config: the model config object.
    target_bbox: [batch, max positive anchors, (dy, dx, log(dh), log(dw))].
        Uses 0 padding to fill in unsed bbox deltas.
    rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
               -1=negative, 0=neutral anchor.
    rpn_bbox: [batch, anchors, (dy, dx, log(dh), log(dw))]
    """
    # Positive anchors contribute to the loss, but negative and
    # neutral anchors (match value of 0 or -1) don't.
    rpn_match = K.squeeze(rpn_match, -1)
    indices = tf.where(K.equal(rpn_match, 1))

    # Pick bbox deltas that contribute to the loss
    rpn_bbox = tf.gather_nd(rpn_bbox, indices)

    # Trim target bounding box deltas to the same length as rpn_bbox.
    batch_counts = K.sum(K.cast(K.equal(rpn_match, 1), tf.int32), axis=1)
    target_bbox = batch_pack_graph(target_bbox, batch_counts,
                                   config.IMAGES_PER_GPU)

    # TODO: use smooth_l1_loss() rather than reimplementing here
    #       to reduce code duplication
    diff = K.abs(target_bbox - rpn_bbox)
    less_than_one = K.cast(K.less(diff, 1.0), "float32")
G
Gyuri Im 已提交
1073
    loss = (less_than_one * 0.5 * diff**2) + (1 - less_than_one) * (diff - 0.5)
W
Waleed Abdulla 已提交
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

    loss = K.switch(tf.size(loss) > 0, K.mean(loss), tf.constant(0.0))
    return loss


def mrcnn_class_loss_graph(target_class_ids, pred_class_logits,
                           active_class_ids):
    """Loss for the classifier head of Mask RCNN.

    target_class_ids: [batch, num_rois]. Integer class IDs. Uses zero
        padding to fill in the array.
    pred_class_logits: [batch, num_rois, num_classes]
    active_class_ids: [batch, num_classes]. Has a value of 1 for
        classes that are in the dataset of the image, and 0
        for classes that are not in the dataset.
    """
    target_class_ids = tf.cast(target_class_ids, 'int64')

    # Find predictions of classes that are not in the dataset.
    pred_class_ids = tf.argmax(pred_class_logits, axis=2)
    # TODO: Update this line to work with batch > 1. Right now it assumes all
    #       images in a batch have the same active_class_ids
    pred_active = tf.gather(active_class_ids[0], pred_class_ids)

    # Loss
    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
        labels=target_class_ids, logits=pred_class_logits)

    # Erase losses of predictions of classes that are not in the active
    # classes of the image.
    loss = loss * pred_active

    # Computer loss mean. Use only predictions that contribute
    # to the loss to get a correct mean.
    loss = tf.reduce_sum(loss) / tf.reduce_sum(pred_active)
    return loss


def mrcnn_bbox_loss_graph(target_bbox, target_class_ids, pred_bbox):
    """Loss for Mask R-CNN bounding box refinement.

    target_bbox: [batch, num_rois, (dy, dx, log(dh), log(dw))]
    target_class_ids: [batch, num_rois]. Integer class IDs.
    pred_bbox: [batch, num_rois, num_classes, (dy, dx, log(dh), log(dw))]
    """
    # Reshape to merge batch and roi dimensions for simplicity.
    target_class_ids = K.reshape(target_class_ids, (-1,))
    target_bbox = K.reshape(target_bbox, (-1, 4))
    pred_bbox = K.reshape(pred_bbox, (-1, K.int_shape(pred_bbox)[2], 4))

    # Only positive ROIs contribute to the loss. And only
    # the right class_id of each ROI. Get their indicies.
    positive_roi_ix = tf.where(target_class_ids > 0)[:, 0]
G
Gyuri Im 已提交
1127 1128
    positive_roi_class_ids = tf.cast(
        tf.gather(target_class_ids, positive_roi_ix), tf.int64)
W
Waleed Abdulla 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    indices = tf.stack([positive_roi_ix, positive_roi_class_ids], axis=1)

    # Gather the deltas (predicted and true) that contribute to loss
    target_bbox = tf.gather(target_bbox, positive_roi_ix)
    pred_bbox = tf.gather_nd(pred_bbox, indices)

    # Smooth-L1 Loss
    loss = K.switch(tf.size(target_bbox) > 0,
                    smooth_l1_loss(y_true=target_bbox, y_pred=pred_bbox),
                    tf.constant(0.0))
    loss = K.mean(loss)
    return loss


def mrcnn_mask_loss_graph(target_masks, target_class_ids, pred_masks):
    """Mask binary cross-entropy loss for the masks head.

    target_masks: [batch, num_rois, height, width].
        A float32 tensor of values 0 or 1. Uses zero padding to fill array.
    target_class_ids: [batch, num_rois]. Integer class IDs. Zero padded.
    pred_masks: [batch, proposals, height, width, num_classes] float32 tensor
                with values from 0 to 1.
    """
    # Reshape for simplicity. Merge first two dimensions into one.
    target_class_ids = K.reshape(target_class_ids, (-1,))
    mask_shape = tf.shape(target_masks)
    target_masks = K.reshape(target_masks, (-1, mask_shape[2], mask_shape[3]))
    pred_shape = tf.shape(pred_masks)
G
Gyuri Im 已提交
1157
    pred_masks = K.reshape(pred_masks,
W
Waleed Abdulla 已提交
1158 1159 1160 1161 1162 1163 1164
                           (-1, pred_shape[2], pred_shape[3], pred_shape[4]))
    # Permute predicted masks to [N, num_classes, height, width]
    pred_masks = tf.transpose(pred_masks, [0, 3, 1, 2])

    # Only positive ROIs contribute to the loss. And only
    # the class specific mask of each ROI.
    positive_ix = tf.where(target_class_ids > 0)[:, 0]
G
Gyuri Im 已提交
1165 1166
    positive_class_ids = tf.cast(
        tf.gather(target_class_ids, positive_ix), tf.int64)
W
Waleed Abdulla 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
    indices = tf.stack([positive_ix, positive_class_ids], axis=1)

    # Gather the masks (predicted and true) that contribute to loss
    y_true = tf.gather(target_masks, positive_ix)
    y_pred = tf.gather_nd(pred_masks, indices)

    # Compute binary cross entropy. If no positive ROIs, then return 0.
    # shape: [batch, roi, num_classes]
    loss = K.switch(tf.size(y_true) > 0,
                    K.binary_crossentropy(target=y_true, output=y_pred),
                    tf.constant(0.0))
    loss = K.mean(loss)
    return loss


############################################################
#  Data Generator
############################################################

W
Waleed Abdulla 已提交
1186
def load_image_gt(dataset, config, image_id, augment=False, augmentation=None,
W
Waleed Abdulla 已提交
1187 1188 1189
                  use_mini_mask=False):
    """Load and return ground truth data for an image (image, mask, bounding boxes).

W
Waleed Abdulla 已提交
1190 1191 1192 1193 1194
    augment: (Depricated. Use augmentation instead). If true, apply random
        image augmentation. Currently, only horizontal flipping is offered.
    augmentation: Optional. An imgaug (https://github.com/aleju/imgaug) augmentation.
        For example, passing imgaug.augmenters.Fliplr(0.5) flips images
        right/left 50% of the time.
W
Waleed Abdulla 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203
    use_mini_mask: If False, returns full-size masks that are the same height
        and width as the original image. These can be big, for example
        1024x1024x100 (for 100 instances). Mini masks are smaller, typically,
        224x224 and are generated by extracting the bounding box of the
        object and resizing it to MINI_MASK_SHAPE.

    Returns:
    image: [height, width, 3]
    shape: the original shape of the image before resizing and cropping.
1204 1205
    class_ids: [instance_count] Integer class IDs
    bbox: [instance_count, (y1, x1, y2, x2)]
W
Waleed Abdulla 已提交
1206 1207 1208 1209 1210 1211 1212
    mask: [height, width, instance_count]. The height and width are those
        of the image unless use_mini_mask is True, in which case they are
        defined in MINI_MASK_SHAPE.
    """
    # Load image and mask
    image = dataset.load_image(image_id)
    mask, class_ids = dataset.load_mask(image_id)
1213
    original_shape = image.shape
W
Waleed Abdulla 已提交
1214
    image, window, scale, padding = utils.resize_image(
G
Gyuri Im 已提交
1215 1216
        image,
        min_dim=config.IMAGE_MIN_DIM,
W
Waleed Abdulla 已提交
1217
        max_dim=config.IMAGE_MAX_DIM,
W
Waleed Abdulla 已提交
1218
        mode=config.IMAGE_RESIZE_MODE)
W
Waleed Abdulla 已提交
1219 1220 1221
    mask = utils.resize_mask(mask, scale, padding)

    # Random horizontal flips.
W
Waleed Abdulla 已提交
1222
    # TODO: will be removed in a future update in favor of augmentation
W
Waleed Abdulla 已提交
1223
    if augment:
W
Waleed Abdulla 已提交
1224
        logging.warning("'augment' is depricated. Use 'augmentation' instead.")
W
Waleed Abdulla 已提交
1225 1226 1227 1228
        if random.randint(0, 1):
            image = np.fliplr(image)
            mask = np.fliplr(mask)

W
Waleed Abdulla 已提交
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    # Augmentation
    # This requires the imgaug lib (https://github.com/aleju/imgaug)
    if augmentation:
        import imgaug

        # Augmentors that are safe to apply to masks
        # Some, such as Affine, have settings that make them unsafe, so always
        # test your augmentation on masks
        MASK_AUGMENTERS = ["Sequential", "SomeOf", "OneOf", "Sometimes",
                           "Fliplr", "Flipud", "CropAndPad",
                           "Affine", "PiecewiseAffine"]

        def hook(images, augmenter, parents, default):
            """Determines which augmenters to apply to masks."""
            return (augmenter.__class__.__name__ in MASK_AUGMENTERS)

W
Waleed Abdulla 已提交
1245
        # Store shapes before augmentation to compare
W
Waleed Abdulla 已提交
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        image_shape = image.shape
        mask_shape = mask.shape
        # Make augmenters deterministic to apply similarly to images and masks
        det = augmentation.to_deterministic()
        image = det.augment_image(image)
        # Change mask to np.uint8 because imgaug doesn't support np.bool
        mask = det.augment_image(mask.astype(np.uint8),
                                 hooks=imgaug.HooksImages(activator=hook))
        # Verify that shapes didn't change
        assert image.shape == image_shape, "Augmentation shouldn't change image size"
        assert mask.shape == mask_shape, "Augmentation shouldn't change mask size"
        # Change mask back to bool
        mask = mask.astype(np.bool)

L
Leo Han 已提交
1260 1261
    # Note that some boxes might be all zeros if the corresponding mask got cropped out.
    # and here is to filter them out
1262
    _idx = np.sum(mask, axis=(0, 1)) > 0
L
Leo Han 已提交
1263
    mask = mask[:, :, _idx]
1264
    class_ids = class_ids[_idx]
W
Waleed Abdulla 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273
    # Bounding boxes. Note that some boxes might be all zeros
    # if the corresponding mask got cropped out.
    # bbox: [num_instances, (y1, x1, y2, x2)]
    bbox = utils.extract_bboxes(mask)

    # Active classes
    # Different datasets have different classes, so track the
    # classes supported in the dataset of this image.
    active_class_ids = np.zeros([dataset.num_classes], dtype=np.int32)
1274 1275
    source_class_ids = dataset.source_class_ids[dataset.image_info[image_id]["source"]]
    active_class_ids[source_class_ids] = 1
W
Waleed Abdulla 已提交
1276 1277 1278 1279 1280 1281

    # Resize masks to smaller size to reduce memory usage
    if use_mini_mask:
        mask = utils.minimize_mask(bbox, mask, config.MINI_MASK_SHAPE)

    # Image meta data
1282 1283
    image_meta = compose_image_meta(image_id, original_shape, image.shape,
                                    window, scale, active_class_ids)
W
Waleed Abdulla 已提交
1284

1285
    return image, image_meta, class_ids, bbox, mask
W
Waleed Abdulla 已提交
1286 1287


1288
def build_detection_targets(rpn_rois, gt_class_ids, gt_boxes, gt_masks, config):
W
Waleed Abdulla 已提交
1289
    """Generate targets for training Stage 2 classifier and mask heads.
1290 1291
    This is not used in normal training. It's useful for debugging or to train
    the Mask RCNN heads without using the RPN head.
W
Waleed Abdulla 已提交
1292 1293 1294

    Inputs:
    rpn_rois: [N, (y1, x1, y2, x2)] proposal boxes.
1295 1296
    gt_class_ids: [instance count] Integer class IDs
    gt_boxes: [instance count, (y1, x1, y2, x2)]
W
Waleed Abdulla 已提交
1297 1298 1299 1300 1301
    gt_masks: [height, width, instance count] Grund truth masks. Can be full
              size or mini-masks.

    Returns:
    rois: [TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)]
1302 1303
    class_ids: [TRAIN_ROIS_PER_IMAGE]. Integer class IDs.
    bboxes: [TRAIN_ROIS_PER_IMAGE, NUM_CLASSES, (y, x, log(h), log(w))]. Class-specific
W
Waleed Abdulla 已提交
1304
            bbox refinements.
W
Waleed Abdulla 已提交
1305 1306 1307 1308
    masks: [TRAIN_ROIS_PER_IMAGE, height, width, NUM_CLASSES). Class specific masks cropped
           to bbox boundaries and resized to neural network output size.
    """
    assert rpn_rois.shape[0] > 0
G
Gyuri Im 已提交
1309 1310 1311 1312 1313 1314
    assert gt_class_ids.dtype == np.int32, "Expected int but got {}".format(
        gt_class_ids.dtype)
    assert gt_boxes.dtype == np.int32, "Expected int but got {}".format(
        gt_boxes.dtype)
    assert gt_masks.dtype == np.bool_, "Expected bool but got {}".format(
        gt_masks.dtype)
W
Waleed Abdulla 已提交
1315 1316 1317 1318 1319

    # It's common to add GT Boxes to ROIs but we don't do that here because
    # according to XinLei Chen's paper, it doesn't help.

    # Trim empty padding in gt_boxes and gt_masks parts
1320
    instance_ids = np.where(gt_class_ids > 0)[0]
W
Waleed Abdulla 已提交
1321
    assert instance_ids.shape[0] > 0, "Image must contain instances."
1322
    gt_class_ids = gt_class_ids[instance_ids]
W
Waleed Abdulla 已提交
1323 1324 1325 1326
    gt_boxes = gt_boxes[instance_ids]
    gt_masks = gt_masks[:, :, instance_ids]

    # Compute areas of ROIs and ground truth boxes.
G
Gyuri Im 已提交
1327 1328 1329 1330
    rpn_roi_area = (rpn_rois[:, 2] - rpn_rois[:, 0]) * \
        (rpn_rois[:, 3] - rpn_rois[:, 1])
    gt_box_area = (gt_boxes[:, 2] - gt_boxes[:, 0]) * \
        (gt_boxes[:, 3] - gt_boxes[:, 1])
W
Waleed Abdulla 已提交
1331 1332 1333 1334

    # Compute overlaps [rpn_rois, gt_boxes]
    overlaps = np.zeros((rpn_rois.shape[0], gt_boxes.shape[0]))
    for i in range(overlaps.shape[1]):
1335
        gt = gt_boxes[i]
G
Gyuri Im 已提交
1336 1337
        overlaps[:, i] = utils.compute_iou(
            gt, rpn_rois, gt_box_area[i], rpn_roi_area)
W
Waleed Abdulla 已提交
1338 1339 1340

    # Assign ROIs to GT boxes
    rpn_roi_iou_argmax = np.argmax(overlaps, axis=1)
G
Gyuri Im 已提交
1341 1342 1343 1344
    rpn_roi_iou_max = overlaps[np.arange(
        overlaps.shape[0]), rpn_roi_iou_argmax]
    # GT box assigned to each ROI
    rpn_roi_gt_boxes = gt_boxes[rpn_roi_iou_argmax]
1345
    rpn_roi_gt_class_ids = gt_class_ids[rpn_roi_iou_argmax]
W
Waleed Abdulla 已提交
1346

1347
    # Positive ROIs are those with >= 0.5 IoU with a GT box.
W
Waleed Abdulla 已提交
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
    fg_ids = np.where(rpn_roi_iou_max > 0.5)[0]

    # Negative ROIs are those with max IoU 0.1-0.5 (hard example mining)
    # TODO: To hard example mine or not to hard example mine, that's the question
#     bg_ids = np.where((rpn_roi_iou_max >= 0.1) & (rpn_roi_iou_max < 0.5))[0]
    bg_ids = np.where(rpn_roi_iou_max < 0.5)[0]

    # Subsample ROIs. Aim for 33% foreground.
    # FG
    fg_roi_count = int(config.TRAIN_ROIS_PER_IMAGE * config.ROI_POSITIVE_RATIO)
    if fg_ids.shape[0] > fg_roi_count:
        keep_fg_ids = np.random.choice(fg_ids, fg_roi_count, replace=False)
    else:
        keep_fg_ids = fg_ids
    # BG
    remaining = config.TRAIN_ROIS_PER_IMAGE - keep_fg_ids.shape[0]
    if bg_ids.shape[0] > remaining:
        keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False)
    else:
        keep_bg_ids = bg_ids
    # Combine indicies of ROIs to keep
    keep = np.concatenate([keep_fg_ids, keep_bg_ids])
    # Need more?
    remaining = config.TRAIN_ROIS_PER_IMAGE - keep.shape[0]
    if remaining > 0:
        # Looks like we don't have enough samples to maintain the desired
        # balance. Reduce requirements and fill in the rest. This is
        # likely different from the Mask RCNN paper.

        # There is a small chance we have neither fg nor bg samples.
        if keep.shape[0] == 0:
            # Pick bg regions with easier IoU threshold
            bg_ids = np.where(rpn_roi_iou_max < 0.5)[0]
            assert bg_ids.shape[0] >= remaining
            keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False)
            assert keep_bg_ids.shape[0] == remaining
            keep = np.concatenate([keep, keep_bg_ids])
        else:
            # Fill the rest with repeated bg rois.
G
Gyuri Im 已提交
1387 1388
            keep_extra_ids = np.random.choice(
                keep_bg_ids, remaining, replace=True)
W
Waleed Abdulla 已提交
1389 1390 1391 1392 1393 1394 1395
            keep = np.concatenate([keep, keep_extra_ids])
    assert keep.shape[0] == config.TRAIN_ROIS_PER_IMAGE, \
        "keep doesn't match ROI batch size {}, {}".format(
            keep.shape[0], config.TRAIN_ROIS_PER_IMAGE)

    # Reset the gt boxes assigned to BG ROIs.
    rpn_roi_gt_boxes[keep_bg_ids, :] = 0
1396
    rpn_roi_gt_class_ids[keep_bg_ids] = 0
W
Waleed Abdulla 已提交
1397 1398

    # For each kept ROI, assign a class_id, and for FG ROIs also add bbox refinement.
1399
    rois = rpn_rois[keep]
W
Waleed Abdulla 已提交
1400
    roi_gt_boxes = rpn_roi_gt_boxes[keep]
1401
    roi_gt_class_ids = rpn_roi_gt_class_ids[keep]
W
Waleed Abdulla 已提交
1402 1403
    roi_gt_assignment = rpn_roi_iou_argmax[keep]

1404
    # Class-aware bbox deltas. [y, x, log(h), log(w)]
G
Gyuri Im 已提交
1405 1406
    bboxes = np.zeros((config.TRAIN_ROIS_PER_IMAGE,
                       config.NUM_CLASSES, 4), dtype=np.float32)
1407
    pos_ids = np.where(roi_gt_class_ids > 0)[0]
G
Gyuri Im 已提交
1408 1409
    bboxes[pos_ids, roi_gt_class_ids[pos_ids]] = utils.box_refinement(
        rois[pos_ids], roi_gt_boxes[pos_ids, :4])
W
Waleed Abdulla 已提交
1410
    # Normalize bbox refinements
1411
    bboxes /= config.BBOX_STD_DEV
W
Waleed Abdulla 已提交
1412

W
Waleed Abdulla 已提交
1413
    # Generate class-specific target masks
G
Gyuri Im 已提交
1414
    masks = np.zeros((config.TRAIN_ROIS_PER_IMAGE, config.MASK_SHAPE[0], config.MASK_SHAPE[1], config.NUM_CLASSES),
W
Waleed Abdulla 已提交
1415 1416
                     dtype=np.float32)
    for i in pos_ids:
1417
        class_id = roi_gt_class_ids[i]
W
Waleed Abdulla 已提交
1418 1419 1420
        assert class_id > 0, "class id must be greater than 0"
        gt_id = roi_gt_assignment[i]
        class_mask = gt_masks[:, :, gt_id]
1421

W
Waleed Abdulla 已提交
1422 1423 1424 1425
        if config.USE_MINI_MASK:
            # Create a mask placeholder, the size of the image
            placeholder = np.zeros(config.IMAGE_SHAPE[:2], dtype=bool)
            # GT box
1426
            gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[gt_id]
W
Waleed Abdulla 已提交
1427 1428 1429 1430
            gt_w = gt_x2 - gt_x1
            gt_h = gt_y2 - gt_y1
            # Resize mini mask to size of GT box
            placeholder[gt_y1:gt_y2, gt_x1:gt_x2] = \
1431
                np.round(skimage.transform.resize(
1432
                    class_mask, (gt_h, gt_w), order=1, mode="constant")).astype(bool)
W
Waleed Abdulla 已提交
1433 1434
            # Place the mini batch in the placeholder
            class_mask = placeholder
1435

W
Waleed Abdulla 已提交
1436
        # Pick part of the mask and resize it
1437
        y1, x1, y2, x2 = rois[i].astype(np.int32)
W
Waleed Abdulla 已提交
1438
        m = class_mask[y1:y2, x1:x2]
1439
        mask = skimage.transform.resize(m, config.MASK_SHAPE, order=1, mode="constant")
1440
        masks[i, :, :, class_id] = mask
W
Waleed Abdulla 已提交
1441

1442
    return rois, roi_gt_class_ids, bboxes, masks
W
Waleed Abdulla 已提交
1443

1444 1445

def build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config):
W
Waleed Abdulla 已提交
1446 1447 1448 1449
    """Given the anchors and GT boxes, compute overlaps and identify positive
    anchors and deltas to refine them to match their corresponding GT boxes.

    anchors: [num_anchors, (y1, x1, y2, x2)]
1450 1451
    gt_class_ids: [num_gt_boxes] Integer class IDs.
    gt_boxes: [num_gt_boxes, (y1, x1, y2, x2)]
W
Waleed Abdulla 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462

    Returns:
    rpn_match: [N] (int32) matches between anchors and GT boxes.
               1 = positive anchor, -1 = negative anchor, 0 = neutral
    rpn_bbox: [N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas.
    """
    # RPN Match: 1 = positive anchor, -1 = negative anchor, 0 = neutral
    rpn_match = np.zeros([anchors.shape[0]], dtype=np.int32)
    # RPN bounding boxes: [max anchors per image, (dy, dx, log(dh), log(dw))]
    rpn_bbox = np.zeros((config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4))

W
Waleed Abdulla 已提交
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
    # Handle COCO crowds
    # A crowd box in COCO is a bounding box around several instances. Exclude
    # them from training. A crowd box is given a negative class ID.
    crowd_ix = np.where(gt_class_ids < 0)[0]
    if crowd_ix.shape[0] > 0:
        # Filter out crowds from ground truth class IDs and boxes
        non_crowd_ix = np.where(gt_class_ids > 0)[0]
        crowd_boxes = gt_boxes[crowd_ix]
        gt_class_ids = gt_class_ids[non_crowd_ix]
        gt_boxes = gt_boxes[non_crowd_ix]
        # Compute overlaps with crowd boxes [anchors, crowds]
        crowd_overlaps = utils.compute_overlaps(anchors, crowd_boxes)
        crowd_iou_max = np.amax(crowd_overlaps, axis=1)
        no_crowd_bool = (crowd_iou_max < 0.001)
    else:
        # All anchors don't intersect a crowd
        no_crowd_bool = np.ones([anchors.shape[0]], dtype=bool)
W
Waleed Abdulla 已提交
1480 1481

    # Compute overlaps [num_anchors, num_gt_boxes]
W
Waleed Abdulla 已提交
1482
    overlaps = utils.compute_overlaps(anchors, gt_boxes)
W
Waleed Abdulla 已提交
1483 1484 1485 1486

    # Match anchors to GT Boxes
    # If an anchor overlaps a GT box with IoU >= 0.7 then it's positive.
    # If an anchor overlaps a GT box with IoU < 0.3 then it's negative.
G
Gyuri Im 已提交
1487
    # Neutral anchors are those that don't match the conditions above,
W
Waleed Abdulla 已提交
1488 1489 1490 1491
    # and they don't influence the loss function.
    # However, don't keep any GT box unmatched (rare, but happens). Instead,
    # match it to the closest anchor (even if its max IoU is < 0.3).
    #
W
Waleed Abdulla 已提交
1492 1493
    # 1. Set negative anchors first. They get overwritten below if a GT box is
    # matched to them. Skip boxes in crowd areas.
W
Waleed Abdulla 已提交
1494 1495
    anchor_iou_argmax = np.argmax(overlaps, axis=1)
    anchor_iou_max = overlaps[np.arange(overlaps.shape[0]), anchor_iou_argmax]
W
Waleed Abdulla 已提交
1496
    rpn_match[(anchor_iou_max < 0.3) & (no_crowd_bool)] = -1
W
Waleed Abdulla 已提交
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    # 2. Set an anchor for each GT box (regardless of IoU value).
    # TODO: If multiple anchors have the same IoU match all of them
    gt_iou_argmax = np.argmax(overlaps, axis=0)
    rpn_match[gt_iou_argmax] = 1
    # 3. Set anchors with high overlap as positive.
    rpn_match[anchor_iou_max >= 0.7] = 1

    # Subsample to balance positive and negative anchors
    # Don't let positives be more than half the anchors
    ids = np.where(rpn_match == 1)[0]
    extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE // 2)
    if extra > 0:
        # Reset the extra ones to neutral
        ids = np.random.choice(ids, extra, replace=False)
        rpn_match[ids] = 0
    # Same for negative proposals
    ids = np.where(rpn_match == -1)[0]
G
Gyuri Im 已提交
1514 1515
    extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE -
                        np.sum(rpn_match == 1))
W
Waleed Abdulla 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524
    if extra > 0:
        # Rest the extra ones to neutral
        ids = np.random.choice(ids, extra, replace=False)
        rpn_match[ids] = 0

    # For positive anchors, compute shift and scale needed to transform them
    # to match the corresponding GT boxes.
    ids = np.where(rpn_match == 1)[0]
    ix = 0  # index into rpn_bbox
W
Waleed Abdulla 已提交
1525
    # TODO: use box_refinement() rather than duplicating the code here
W
Waleed Abdulla 已提交
1526 1527
    for i, a in zip(ids, anchors[ids]):
        # Closest gt box (it might have IoU < 0.7)
1528
        gt = gt_boxes[anchor_iou_argmax[i]]
W
Waleed Abdulla 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

        # Convert coordinates to center plus width/height.
        # GT Box
        gt_h = gt[2] - gt[0]
        gt_w = gt[3] - gt[1]
        gt_center_y = gt[0] + 0.5 * gt_h
        gt_center_x = gt[1] + 0.5 * gt_w
        # Anchor
        a_h = a[2] - a[0]
        a_w = a[3] - a[1]
        a_center_y = a[0] + 0.5 * a_h
        a_center_x = a[1] + 0.5 * a_w

        # Compute the bbox refinement that the RPN should predict.
        rpn_bbox[ix] = [
            (gt_center_y - a_center_y) / a_h,
            (gt_center_x - a_center_x) / a_w,
            np.log(gt_h / a_h),
            np.log(gt_w / a_w),
        ]
        # Normalize
        rpn_bbox[ix] /= config.RPN_BBOX_STD_DEV
        ix += 1

    return rpn_match, rpn_bbox


1556
def generate_random_rois(image_shape, count, gt_class_ids, gt_boxes):
W
Waleed Abdulla 已提交
1557 1558 1559 1560 1561
    """Generates ROI proposals similar to what a region proposal network
    would generate.

    image_shape: [Height, Width, Depth]
    count: Number of ROIs to generate
1562 1563
    gt_class_ids: [N] Integer ground truth class IDs
    gt_boxes: [N, (y1, x1, y2, x2)] Ground truth boxes in pixels.
W
Waleed Abdulla 已提交
1564 1565 1566 1567 1568

    Returns: [count, (y1, x1, y2, x2)] ROI boxes in pixels.
    """
    # placeholder
    rois = np.zeros((count, 4), dtype=np.int32)
1569

W
Waleed Abdulla 已提交
1570 1571 1572
    # Generate random ROIs around GT boxes (90% of count)
    rois_per_box = int(0.9 * count / gt_boxes.shape[0])
    for i in range(gt_boxes.shape[0]):
1573
        gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[i]
W
Waleed Abdulla 已提交
1574 1575 1576
        h = gt_y2 - gt_y1
        w = gt_x2 - gt_x1
        # random boundaries
G
Gyuri Im 已提交
1577 1578 1579 1580
        r_y1 = max(gt_y1 - h, 0)
        r_y2 = min(gt_y2 + h, image_shape[0])
        r_x1 = max(gt_x1 - w, 0)
        r_x2 = min(gt_x2 + w, image_shape[1])
1581

W
Waleed Abdulla 已提交
1582
        # To avoid generating boxes with zero area, we generate double what
G
Gyuri Im 已提交
1583
        # we need and filter out the extra. If we get fewer valid boxes
W
Waleed Abdulla 已提交
1584 1585
        # than we need, we loop and try again.
        while True:
G
Gyuri Im 已提交
1586 1587
            y1y2 = np.random.randint(r_y1, r_y2, (rois_per_box * 2, 2))
            x1x2 = np.random.randint(r_x1, r_x2, (rois_per_box * 2, 2))
W
Waleed Abdulla 已提交
1588 1589
            # Filter out zero area boxes
            threshold = 1
G
Gyuri Im 已提交
1590 1591 1592 1593
            y1y2 = y1y2[np.abs(y1y2[:, 0] - y1y2[:, 1]) >=
                        threshold][:rois_per_box]
            x1x2 = x1x2[np.abs(x1x2[:, 0] - x1x2[:, 1]) >=
                        threshold][:rois_per_box]
W
Waleed Abdulla 已提交
1594 1595
            if y1y2.shape[0] == rois_per_box and x1x2.shape[0] == rois_per_box:
                break
1596

W
Waleed Abdulla 已提交
1597 1598 1599 1600 1601
        # Sort on axis 1 to ensure x1 <= x2 and y1 <= y2 and then reshape
        # into x1, y1, x2, y2 order
        x1, x2 = np.split(np.sort(x1x2, axis=1), 2, axis=1)
        y1, y2 = np.split(np.sort(y1y2, axis=1), 2, axis=1)
        box_rois = np.hstack([y1, x1, y2, x2])
G
Gyuri Im 已提交
1602
        rois[rois_per_box * i:rois_per_box * (i + 1)] = box_rois
1603

W
Waleed Abdulla 已提交
1604 1605 1606
    # Generate random ROIs anywhere in the image (10% of count)
    remaining_count = count - (rois_per_box * gt_boxes.shape[0])
    # To avoid generating boxes with zero area, we generate double what
G
Gyuri Im 已提交
1607
    # we need and filter out the extra. If we get fewer valid boxes
W
Waleed Abdulla 已提交
1608 1609 1610 1611 1612 1613
    # than we need, we loop and try again.
    while True:
        y1y2 = np.random.randint(0, image_shape[0], (remaining_count * 2, 2))
        x1x2 = np.random.randint(0, image_shape[1], (remaining_count * 2, 2))
        # Filter out zero area boxes
        threshold = 1
G
Gyuri Im 已提交
1614 1615 1616 1617
        y1y2 = y1y2[np.abs(y1y2[:, 0] - y1y2[:, 1]) >=
                    threshold][:remaining_count]
        x1x2 = x1x2[np.abs(x1x2[:, 0] - x1x2[:, 1]) >=
                    threshold][:remaining_count]
W
Waleed Abdulla 已提交
1618 1619
        if y1y2.shape[0] == remaining_count and x1x2.shape[0] == remaining_count:
            break
1620

W
Waleed Abdulla 已提交
1621 1622 1623 1624 1625 1626 1627 1628 1629
    # Sort on axis 1 to ensure x1 <= x2 and y1 <= y2 and then reshape
    # into x1, y1, x2, y2 order
    x1, x2 = np.split(np.sort(x1x2, axis=1), 2, axis=1)
    y1, y2 = np.split(np.sort(y1y2, axis=1), 2, axis=1)
    global_rois = np.hstack([y1, x1, y2, x2])
    rois[-remaining_count:] = global_rois
    return rois


W
Waleed Abdulla 已提交
1630 1631
def data_generator(dataset, config, shuffle=True, augment=False, augmentation=None,
                   random_rois=0, batch_size=1, detection_targets=False):
G
Gyuri Im 已提交
1632
    """A generator that returns images and corresponding target class ids,
W
Waleed Abdulla 已提交
1633 1634 1635 1636 1637
    bounding box deltas, and masks.

    dataset: The Dataset object to pick data from
    config: The model config object
    shuffle: If True, shuffles the samples before every epoch
W
Waleed Abdulla 已提交
1638 1639 1640 1641 1642
    augment: (Depricated. Use augmentation instead). If true, apply random
        image augmentation. Currently, only horizontal flipping is offered.
    augmentation: Optional. An imgaug (https://github.com/aleju/imgaug) augmentation.
        For example, passing imgaug.augmenters.Fliplr(0.5) flips images
        right/left 50% of the time.
W
Waleed Abdulla 已提交
1643 1644 1645 1646 1647 1648 1649 1650
    random_rois: If > 0 then generate proposals to be used to train the
                 network classifier and mask heads. Useful if training
                 the Mask RCNN part without the RPN.
    batch_size: How many images to return in each call
    detection_targets: If True, generate detection targets (class IDs, bbox
        deltas, and masks). Typically for debugging or visualizations because
        in trainig detection targets are generated by DetectionTargetLayer.

G
Gyuri Im 已提交
1651
    Returns a Python generator. Upon calling next() on it, the
W
Waleed Abdulla 已提交
1652 1653 1654 1655
    generator returns two lists, inputs and outputs. The containtes
    of the lists differs depending on the received arguments:
    inputs list:
    - images: [batch, H, W, C]
1656
    - image_meta: [batch, (meta data)] Image details. See compose_image_meta()
W
Waleed Abdulla 已提交
1657 1658
    - rpn_match: [batch, N] Integer (1=positive anchor, -1=negative, 0=neutral)
    - rpn_bbox: [batch, N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas.
1659 1660
    - gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class IDs
    - gt_boxes: [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)]
W
Waleed Abdulla 已提交
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
    - gt_masks: [batch, height, width, MAX_GT_INSTANCES]. The height and width
                are those of the image unless use_mini_mask is True, in which
                case they are defined in MINI_MASK_SHAPE.

    outputs list: Usually empty in regular training. But if detection_targets
        is True then the outputs list contains target class_ids, bbox deltas,
        and masks.
    """
    b = 0  # batch item index
    image_index = -1
    image_ids = np.copy(dataset.image_ids)
    error_count = 0

    # Anchors
    # [anchor_count, (y1, x1, y2, x2)]
1676
    backbone_shapes = compute_backbone_shapes(config, config.IMAGE_SHAPE)
G
Gyuri Im 已提交
1677 1678
    anchors = utils.generate_pyramid_anchors(config.RPN_ANCHOR_SCALES,
                                             config.RPN_ANCHOR_RATIOS,
1679
                                             backbone_shapes,
G
Gyuri Im 已提交
1680 1681
                                             config.BACKBONE_STRIDES,
                                             config.RPN_ANCHOR_STRIDE)
W
Waleed Abdulla 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692

    # Keras requires a generator to run indefinately.
    while True:
        try:
            # Increment index to pick next image. Shuffle if at the start of an epoch.
            image_index = (image_index + 1) % len(image_ids)
            if shuffle and image_index == 0:
                np.random.shuffle(image_ids)

            # Get GT bounding boxes and masks for image.
            image_id = image_ids[image_index]
1693
            image, image_meta, gt_class_ids, gt_boxes, gt_masks = \
W
Waleed Abdulla 已提交
1694
                load_image_gt(dataset, config, image_id, augment=augment,
W
Waleed Abdulla 已提交
1695
                              augmentation=augmentation,
W
Waleed Abdulla 已提交
1696
                              use_mini_mask=config.USE_MINI_MASK)
G
Gyuri Im 已提交
1697

1698
            # Skip images that have no instances. This can happen in cases
W
Waleed Abdulla 已提交
1699 1700
            # where we train on a subset of classes and the image doesn't
            # have any of the classes we care about.
W
Waleed Abdulla 已提交
1701
            if not np.any(gt_class_ids > 0):
W
Waleed Abdulla 已提交
1702 1703 1704
                continue

            # RPN Targets
1705 1706
            rpn_match, rpn_bbox = build_rpn_targets(image.shape, anchors,
                                                    gt_class_ids, gt_boxes, config)
W
Waleed Abdulla 已提交
1707 1708 1709

            # Mask R-CNN Targets
            if random_rois:
G
Gyuri Im 已提交
1710 1711
                rpn_rois = generate_random_rois(
                    image.shape, random_rois, gt_class_ids, gt_boxes)
W
Waleed Abdulla 已提交
1712 1713
                if detection_targets:
                    rois, mrcnn_class_ids, mrcnn_bbox, mrcnn_mask =\
G
Gyuri Im 已提交
1714 1715
                        build_detection_targets(
                            rpn_rois, gt_class_ids, gt_boxes, gt_masks, config)
W
Waleed Abdulla 已提交
1716 1717 1718

            # Init batch arrays
            if b == 0:
G
Gyuri Im 已提交
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
                batch_image_meta = np.zeros(
                    (batch_size,) + image_meta.shape, dtype=image_meta.dtype)
                batch_rpn_match = np.zeros(
                    [batch_size, anchors.shape[0], 1], dtype=rpn_match.dtype)
                batch_rpn_bbox = np.zeros(
                    [batch_size, config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4], dtype=rpn_bbox.dtype)
                batch_images = np.zeros(
                    (batch_size,) + image.shape, dtype=np.float32)
                batch_gt_class_ids = np.zeros(
                    (batch_size, config.MAX_GT_INSTANCES), dtype=np.int32)
                batch_gt_boxes = np.zeros(
                    (batch_size, config.MAX_GT_INSTANCES, 4), dtype=np.int32)
W
Waleed Abdulla 已提交
1731
                if config.USE_MINI_MASK:
G
Gyuri Im 已提交
1732
                    batch_gt_masks = np.zeros((batch_size, config.MINI_MASK_SHAPE[0], config.MINI_MASK_SHAPE[1],
W
Waleed Abdulla 已提交
1733 1734
                                               config.MAX_GT_INSTANCES))
                else:
G
Gyuri Im 已提交
1735 1736
                    batch_gt_masks = np.zeros(
                        (batch_size, image.shape[0], image.shape[1], config.MAX_GT_INSTANCES))
W
Waleed Abdulla 已提交
1737
                if random_rois:
G
Gyuri Im 已提交
1738 1739
                    batch_rpn_rois = np.zeros(
                        (batch_size, rpn_rois.shape[0], 4), dtype=rpn_rois.dtype)
W
Waleed Abdulla 已提交
1740
                    if detection_targets:
G
Gyuri Im 已提交
1741 1742 1743 1744 1745 1746 1747 1748
                        batch_rois = np.zeros(
                            (batch_size,) + rois.shape, dtype=rois.dtype)
                        batch_mrcnn_class_ids = np.zeros(
                            (batch_size,) + mrcnn_class_ids.shape, dtype=mrcnn_class_ids.dtype)
                        batch_mrcnn_bbox = np.zeros(
                            (batch_size,) + mrcnn_bbox.shape, dtype=mrcnn_bbox.dtype)
                        batch_mrcnn_mask = np.zeros(
                            (batch_size,) + mrcnn_mask.shape, dtype=mrcnn_mask.dtype)
W
Waleed Abdulla 已提交
1749 1750 1751

            # If more instances than fits in the array, sub-sample from them.
            if gt_boxes.shape[0] > config.MAX_GT_INSTANCES:
G
Gyuri Im 已提交
1752 1753
                ids = np.random.choice(
                    np.arange(gt_boxes.shape[0]), config.MAX_GT_INSTANCES, replace=False)
1754
                gt_class_ids = gt_class_ids[ids]
W
Waleed Abdulla 已提交
1755
                gt_boxes = gt_boxes[ids]
G
Gyuri Im 已提交
1756
                gt_masks = gt_masks[:, :, ids]
W
Waleed Abdulla 已提交
1757 1758 1759 1760 1761 1762

            # Add to batch
            batch_image_meta[b] = image_meta
            batch_rpn_match[b] = rpn_match[:, np.newaxis]
            batch_rpn_bbox[b] = rpn_bbox
            batch_images[b] = mold_image(image.astype(np.float32), config)
G
Gyuri Im 已提交
1763 1764 1765
            batch_gt_class_ids[b, :gt_class_ids.shape[0]] = gt_class_ids
            batch_gt_boxes[b, :gt_boxes.shape[0]] = gt_boxes
            batch_gt_masks[b, :, :, :gt_masks.shape[-1]] = gt_masks
W
Waleed Abdulla 已提交
1766
            if random_rois:
1767
                batch_rpn_rois[b] = rpn_rois
W
Waleed Abdulla 已提交
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
                if detection_targets:
                    batch_rois[b] = rois
                    batch_mrcnn_class_ids[b] = mrcnn_class_ids
                    batch_mrcnn_bbox[b] = mrcnn_bbox
                    batch_mrcnn_mask[b] = mrcnn_mask
            b += 1

            # Batch full?
            if b >= batch_size:
                inputs = [batch_images, batch_image_meta, batch_rpn_match, batch_rpn_bbox,
1778
                          batch_gt_class_ids, batch_gt_boxes, batch_gt_masks]
W
Waleed Abdulla 已提交
1779 1780 1781 1782 1783 1784 1785
                outputs = []

                if random_rois:
                    inputs.extend([batch_rpn_rois])
                    if detection_targets:
                        inputs.extend([batch_rois])
                        # Keras requires that output and targets have the same number of dimensions
G
Gyuri Im 已提交
1786 1787 1788 1789
                        batch_mrcnn_class_ids = np.expand_dims(
                            batch_mrcnn_class_ids, -1)
                        outputs.extend(
                            [batch_mrcnn_class_ids, batch_mrcnn_bbox, batch_mrcnn_mask])
W
Waleed Abdulla 已提交
1790 1791 1792 1793 1794 1795 1796 1797 1798

                yield inputs, outputs

                # start a new batch
                b = 0
        except (GeneratorExit, KeyboardInterrupt):
            raise
        except:
            # Log it and skip the image
G
Gyuri Im 已提交
1799 1800
            logging.exception("Error processing image {}".format(
                dataset.image_info[image_id]))
W
Waleed Abdulla 已提交
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
            error_count += 1
            if error_count > 5:
                raise


############################################################
#  MaskRCNN Class
############################################################

class MaskRCNN():
    """Encapsulates the Mask RCNN model functionality.

    The actual Keras model is in the keras_model property.
    """
G
Gyuri Im 已提交
1815

W
Waleed Abdulla 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
    def __init__(self, mode, config, model_dir):
        """
        mode: Either "training" or "inference"
        config: A Sub-class of the Config class
        model_dir: Directory to save training logs and trained weights
        """
        assert mode in ['training', 'inference']
        self.mode = mode
        self.config = config
        self.model_dir = model_dir
        self.set_log_dir()
        self.keras_model = self.build(mode=mode, config=config)

    def build(self, mode, config):
        """Build Mask R-CNN architecture.
            input_shape: The shape of the input image.
G
Gyuri Im 已提交
1832
            mode: Either "training" or "inference". The inputs and
W
Waleed Abdulla 已提交
1833 1834 1835
                outputs of the model differ accordingly.
        """
        assert mode in ['training', 'inference']
G
Gyuri Im 已提交
1836

W
Waleed Abdulla 已提交
1837 1838
        # Image size must be dividable by 2 multiple times
        h, w = config.IMAGE_SHAPE[:2]
G
Gyuri Im 已提交
1839
        if h / 2**6 != int(h / 2**6) or w / 2**6 != int(w / 2**6):
W
Waleed Abdulla 已提交
1840 1841 1842
            raise Exception("Image size must be dividable by 2 at least 6 times "
                            "to avoid fractions when downscaling and upscaling."
                            "For example, use 256, 320, 384, 448, 512, ... etc. ")
G
Gyuri Im 已提交
1843

W
Waleed Abdulla 已提交
1844
        # Inputs
G
Gyuri Im 已提交
1845
        input_image = KL.Input(
1846
            shape=[None, None, 3], name="input_image")
1847 1848
        input_image_meta = KL.Input(shape=[config.IMAGE_META_SIZE],
                                    name="input_image_meta")
W
Waleed Abdulla 已提交
1849 1850
        if mode == "training":
            # RPN GT
G
Gyuri Im 已提交
1851 1852 1853 1854
            input_rpn_match = KL.Input(
                shape=[None, 1], name="input_rpn_match", dtype=tf.int32)
            input_rpn_bbox = KL.Input(
                shape=[None, 4], name="input_rpn_bbox", dtype=tf.float32)
1855 1856 1857

            # Detection GT (class IDs, bounding boxes, and masks)
            # 1. GT Class IDs (zero padded)
G
Gyuri Im 已提交
1858 1859
            input_gt_class_ids = KL.Input(
                shape=[None], name="input_gt_class_ids", dtype=tf.int32)
1860 1861
            # 2. GT Boxes in pixels (zero padded)
            # [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)] in image coordinates
G
Gyuri Im 已提交
1862 1863
            input_gt_boxes = KL.Input(
                shape=[None, 4], name="input_gt_boxes", dtype=tf.float32)
W
Waleed Abdulla 已提交
1864
            # Normalize coordinates
1865 1866
            gt_boxes = KL.Lambda(lambda x: norm_boxes_graph(
                x, K.shape(input_image)[1:3]))(input_gt_boxes)
1867
            # 3. GT Masks (zero padded)
W
Waleed Abdulla 已提交
1868 1869 1870
            # [batch, height, width, MAX_GT_INSTANCES]
            if config.USE_MINI_MASK:
                input_gt_masks = KL.Input(
G
Gyuri Im 已提交
1871 1872
                    shape=[config.MINI_MASK_SHAPE[0],
                           config.MINI_MASK_SHAPE[1], None],
W
Waleed Abdulla 已提交
1873 1874 1875 1876 1877
                    name="input_gt_masks", dtype=bool)
            else:
                input_gt_masks = KL.Input(
                    shape=[config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1], None],
                    name="input_gt_masks", dtype=bool)
1878 1879 1880
        elif mode == "inference":
            # Anchors in normalized coordinates
            input_anchors = KL.Input(shape=[None, 4], name="input_anchors")
G
Gyuri Im 已提交
1881

W
Waleed Abdulla 已提交
1882 1883 1884 1885
        # Build the shared convolutional layers.
        # Bottom-up Layers
        # Returns a list of the last layers of each stage, 5 in total.
        # Don't create the thead (stage 5), so we pick the 4th item in the list.
1886 1887
        _, C2, C3, C4, C5 = resnet_graph(input_image, config.BACKBONE,
                                         stage5=True, train_bn=config.TRAIN_BN)
W
Waleed Abdulla 已提交
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
        # Top-down Layers
        # TODO: add assert to varify feature map sizes match what's in config
        P5 = KL.Conv2D(256, (1, 1), name='fpn_c5p5')(C5)
        P4 = KL.Add(name="fpn_p4add")([
            KL.UpSampling2D(size=(2, 2), name="fpn_p5upsampled")(P5),
            KL.Conv2D(256, (1, 1), name='fpn_c4p4')(C4)])
        P3 = KL.Add(name="fpn_p3add")([
            KL.UpSampling2D(size=(2, 2), name="fpn_p4upsampled")(P4),
            KL.Conv2D(256, (1, 1), name='fpn_c3p3')(C3)])
        P2 = KL.Add(name="fpn_p2add")([
            KL.UpSampling2D(size=(2, 2), name="fpn_p3upsampled")(P3),
            KL.Conv2D(256, (1, 1), name='fpn_c2p2')(C2)])
        # Attach 3x3 conv to all P layers to get the final feature maps.
        P2 = KL.Conv2D(256, (3, 3), padding="SAME", name="fpn_p2")(P2)
        P3 = KL.Conv2D(256, (3, 3), padding="SAME", name="fpn_p3")(P3)
        P4 = KL.Conv2D(256, (3, 3), padding="SAME", name="fpn_p4")(P4)
        P5 = KL.Conv2D(256, (3, 3), padding="SAME", name="fpn_p5")(P5)
        # P6 is used for the 5th anchor scale in RPN. Generated by
        # subsampling from P5 with stride of 2.
        P6 = KL.MaxPooling2D(pool_size=(1, 1), strides=2, name="fpn_p6")(P5)
G
Gyuri Im 已提交
1908

W
Waleed Abdulla 已提交
1909 1910 1911
        # Note that P6 is used in RPN, but not in the classifier heads.
        rpn_feature_maps = [P2, P3, P4, P5, P6]
        mrcnn_feature_maps = [P2, P3, P4, P5]
G
Gyuri Im 已提交
1912

1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
        # Anchors
        if mode == "training":
            anchors = self.get_anchors(config.IMAGE_SHAPE)
            # Duplicate across the batch dimension because Keras requires it
            # TODO: can this be optimized to avoid duplicating the anchors?
            anchors = np.broadcast_to(anchors, (config.BATCH_SIZE,) + anchors.shape)
            # A hack to get around Keras's bad support for constants
            anchors = KL.Lambda(lambda x: tf.constant(anchors), name="anchors")(input_image)
        else:
            anchors = input_anchors
G
Gyuri Im 已提交
1923

W
Waleed Abdulla 已提交
1924
        # RPN Model
G
Gyuri Im 已提交
1925
        rpn = build_rpn_model(config.RPN_ANCHOR_STRIDE,
W
Waleed Abdulla 已提交
1926 1927 1928 1929 1930 1931
                              len(config.RPN_ANCHOR_RATIOS), 256)
        # Loop through pyramid layers
        layer_outputs = []  # list of lists
        for p in rpn_feature_maps:
            layer_outputs.append(rpn([p]))
        # Concatenate layer outputs
G
Gyuri Im 已提交
1932 1933
        # Convert from list of lists of level outputs to list of lists
        # of outputs across levels.
W
Waleed Abdulla 已提交
1934 1935 1936
        # e.g. [[a1, b1, c1], [a2, b2, c2]] => [[a1, a2], [b1, b2], [c1, c2]]
        output_names = ["rpn_class_logits", "rpn_class", "rpn_bbox"]
        outputs = list(zip(*layer_outputs))
G
Gyuri Im 已提交
1937 1938 1939
        outputs = [KL.Concatenate(axis=1, name=n)(list(o))
                   for o, n in zip(outputs, output_names)]

W
Waleed Abdulla 已提交
1940 1941 1942
        rpn_class_logits, rpn_class, rpn_bbox = outputs

        # Generate proposals
W
Waleed Abdulla 已提交
1943 1944
        # Proposals are [batch, N, (y1, x1, y2, x2)] in normalized coordinates
        # and zero padded.
W
Waleed Abdulla 已提交
1945
        proposal_count = config.POST_NMS_ROIS_TRAINING if mode == "training"\
G
Gyuri Im 已提交
1946
            else config.POST_NMS_ROIS_INFERENCE
1947 1948 1949 1950 1951
        rpn_rois = ProposalLayer(
            proposal_count=proposal_count,
            nms_threshold=config.RPN_NMS_THRESHOLD,
            name="ROI",
            config=config)([rpn_class, rpn_bbox, anchors])
W
Waleed Abdulla 已提交
1952 1953 1954 1955

        if mode == "training":
            # Class ID mask to mark class IDs supported by the dataset the image
            # came from.
1956 1957 1958
            active_class_ids = KL.Lambda(
                lambda x: parse_image_meta_graph(x)["active_class_ids"]
                )(input_image_meta)
W
Waleed Abdulla 已提交
1959 1960 1961 1962

            if not config.USE_RPN_ROIS:
                # Ignore predicted ROIs and use ROIs provided as an input.
                input_rois = KL.Input(shape=[config.POST_NMS_ROIS_TRAINING, 4],
G
Gyuri Im 已提交
1963
                                      name="input_roi", dtype=np.int32)
1964 1965 1966
                # Normalize coordinates
                target_rois = KL.Lambda(lambda x: norm_boxes_graph(
                    x, K.shape(input_image)[1:3]))(input_rois)
W
Waleed Abdulla 已提交
1967 1968 1969 1970 1971
            else:
                target_rois = rpn_rois

            # Generate detection targets
            # Subsamples proposals and generates target outputs for training
1972 1973
            # Note that proposal class IDs, gt_boxes, and gt_masks are zero
            # padded. Equally, returned rois and targets are zero padded.
W
Waleed Abdulla 已提交
1974 1975
            rois, target_class_ids, target_bbox, target_mask =\
                DetectionTargetLayer(config, name="proposal_targets")([
1976
                    target_rois, input_gt_class_ids, gt_boxes, input_gt_masks])
W
Waleed Abdulla 已提交
1977 1978 1979 1980

            # Network Heads
            # TODO: verify that this handles zero padded ROIs
            mrcnn_class_logits, mrcnn_class, mrcnn_bbox =\
1981
                fpn_classifier_graph(rois, mrcnn_feature_maps, input_image_meta,
1982 1983
                                     config.POOL_SIZE, config.NUM_CLASSES,
                                     train_bn=config.TRAIN_BN)
G
Gyuri Im 已提交
1984

W
Waleed Abdulla 已提交
1985
            mrcnn_mask = build_fpn_mask_graph(rois, mrcnn_feature_maps,
1986
                                              input_image_meta,
W
Waleed Abdulla 已提交
1987
                                              config.MASK_POOL_SIZE,
1988 1989
                                              config.NUM_CLASSES,
                                              train_bn=config.TRAIN_BN)
W
Waleed Abdulla 已提交
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006

            # TODO: clean up (use tf.identify if necessary)
            output_rois = KL.Lambda(lambda x: x * 1, name="output_rois")(rois)

            # Losses
            rpn_class_loss = KL.Lambda(lambda x: rpn_class_loss_graph(*x), name="rpn_class_loss")(
                [input_rpn_match, rpn_class_logits])
            rpn_bbox_loss = KL.Lambda(lambda x: rpn_bbox_loss_graph(config, *x), name="rpn_bbox_loss")(
                [input_rpn_bbox, input_rpn_match, rpn_bbox])
            class_loss = KL.Lambda(lambda x: mrcnn_class_loss_graph(*x), name="mrcnn_class_loss")(
                [target_class_ids, mrcnn_class_logits, active_class_ids])
            bbox_loss = KL.Lambda(lambda x: mrcnn_bbox_loss_graph(*x), name="mrcnn_bbox_loss")(
                [target_bbox, target_class_ids, mrcnn_bbox])
            mask_loss = KL.Lambda(lambda x: mrcnn_mask_loss_graph(*x), name="mrcnn_mask_loss")(
                [target_mask, target_class_ids, mrcnn_mask])

            # Model
G
Gyuri Im 已提交
2007 2008
            inputs = [input_image, input_image_meta,
                      input_rpn_match, input_rpn_bbox, input_gt_class_ids, input_gt_boxes, input_gt_masks]
W
Waleed Abdulla 已提交
2009 2010 2011
            if not config.USE_RPN_ROIS:
                inputs.append(input_rois)
            outputs = [rpn_class_logits, rpn_class, rpn_bbox,
G
Gyuri Im 已提交
2012 2013 2014
                       mrcnn_class_logits, mrcnn_class, mrcnn_bbox, mrcnn_mask,
                       rpn_rois, output_rois,
                       rpn_class_loss, rpn_bbox_loss, class_loss, bbox_loss, mask_loss]
W
Waleed Abdulla 已提交
2015 2016 2017 2018 2019
            model = KM.Model(inputs, outputs, name='mask_rcnn')
        else:
            # Network Heads
            # Proposal classifier and BBox regressor heads
            mrcnn_class_logits, mrcnn_class, mrcnn_bbox =\
2020
                fpn_classifier_graph(rpn_rois, mrcnn_feature_maps, input_image_meta,
2021 2022
                                     config.POOL_SIZE, config.NUM_CLASSES,
                                     train_bn=config.TRAIN_BN)
W
Waleed Abdulla 已提交
2023 2024

            # Detections
2025 2026
            # output is [batch, num_detections, (y1, x1, y2, x2, class_id, score)] in 
            # normalized coordinates
W
Waleed Abdulla 已提交
2027 2028 2029 2030
            detections = DetectionLayer(config, name="mrcnn_detection")(
                [rpn_rois, mrcnn_class, mrcnn_bbox, input_image_meta])

            # Create masks for detections
2031
            detection_boxes = KL.Lambda(lambda x: x[..., :4])(detections)
W
Waleed Abdulla 已提交
2032
            mrcnn_mask = build_fpn_mask_graph(detection_boxes, mrcnn_feature_maps,
2033
                                              input_image_meta,
W
Waleed Abdulla 已提交
2034
                                              config.MASK_POOL_SIZE,
2035 2036
                                              config.NUM_CLASSES,
                                              train_bn=config.TRAIN_BN)
W
Waleed Abdulla 已提交
2037

2038
            model = KM.Model([input_image, input_image_meta, input_anchors],
G
Gyuri Im 已提交
2039 2040 2041 2042
                             [detections, mrcnn_class, mrcnn_bbox,
                                 mrcnn_mask, rpn_rois, rpn_class, rpn_bbox],
                             name='mask_rcnn')

W
Waleed Abdulla 已提交
2043 2044 2045 2046
        # Add multi-GPU support.
        if config.GPU_COUNT > 1:
            from parallel_model import ParallelModel
            model = ParallelModel(model, config.GPU_COUNT)
G
Gyuri Im 已提交
2047

W
Waleed Abdulla 已提交
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
        return model

    def find_last(self):
        """Finds the last checkpoint file of the last trained model in the
        model directory.
        Returns:
            log_dir: The directory where events and weights are saved
            checkpoint_path: the path to the last checkpoint file
        """
        # Get directory names. Each directory corresponds to a model
        dir_names = next(os.walk(self.model_dir))[1]
        key = self.config.NAME.lower()
        dir_names = filter(lambda f: f.startswith(key), dir_names)
        dir_names = sorted(dir_names)
        if not dir_names:
            return None, None
        # Pick last directory
        dir_name = os.path.join(self.model_dir, dir_names[-1])
        # Find the last checkpoint
        checkpoints = next(os.walk(dir_name))[2]
        checkpoints = filter(lambda f: f.startswith("mask_rcnn"), checkpoints)
        checkpoints = sorted(checkpoints)
        if not checkpoints:
            return dir_name, None
        checkpoint = os.path.join(dir_name, checkpoints[-1])
        return dir_name, checkpoint

    def load_weights(self, filepath, by_name=False, exclude=None):
        """Modified version of the correspoding Keras function with
        the addition of multi-GPU support and the ability to exclude
        some layers from loading.
        exlude: list of layer names to excluce
        """
        import h5py
        from keras.engine import topology

        if exclude:
            by_name = True

        if h5py is None:
            raise ImportError('`load_weights` requires h5py.')
        f = h5py.File(filepath, mode='r')
        if 'layer_names' not in f.attrs and 'model_weights' in f:
            f = f['model_weights']

        # In multi-GPU training, we wrap the model. Get layers
        # of the inner model because they have the weights.
        keras_model = self.keras_model
        layers = keras_model.inner_model.layers if hasattr(keras_model, "inner_model")\
            else keras_model.layers

        # Exclude some layers
        if exclude:
            layers = filter(lambda l: l.name not in exclude, layers)
G
Gyuri Im 已提交
2102

W
Waleed Abdulla 已提交
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
        if by_name:
            topology.load_weights_from_hdf5_group_by_name(f, layers)
        else:
            topology.load_weights_from_hdf5_group(f, layers)
        if hasattr(f, 'close'):
            f.close()

        # Update the log directory
        self.set_log_dir(filepath)

    def get_imagenet_weights(self):
        """Downloads ImageNet trained weights from Keras.
        Returns path to weights file.
        """
        from keras.utils.data_utils import get_file
        TF_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/'\
                                 'releases/download/v0.2/'\
                                 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'
        weights_path = get_file('resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5',
                                TF_WEIGHTS_PATH_NO_TOP,
                                cache_subdir='models',
                                md5_hash='a268eb855778b3df3c7506639542a6af')
        return weights_path
G
Gyuri Im 已提交
2126

W
Waleed Abdulla 已提交
2127 2128 2129 2130 2131 2132
    def compile(self, learning_rate, momentum):
        """Gets the model ready for training. Adds losses, regularization, and
        metrics. Then calls the Keras compile() function.
        """
        # Optimizer object
        optimizer = keras.optimizers.SGD(lr=learning_rate, momentum=momentum,
2133
                                         clipnorm=self.config.GRADIENT_CLIP_NORM)
W
Waleed Abdulla 已提交
2134 2135 2136 2137 2138
        # Add Losses
        # First, clear previously set losses to avoid duplication
        self.keras_model._losses = []
        self.keras_model._per_input_losses = {}
        loss_names = ["rpn_class_loss", "rpn_bbox_loss",
G
Gyuri Im 已提交
2139
                      "mrcnn_class_loss", "mrcnn_bbox_loss", "mrcnn_mask_loss"]
W
Waleed Abdulla 已提交
2140 2141 2142 2143
        for name in loss_names:
            layer = self.keras_model.get_layer(name)
            if layer.output in self.keras_model.losses:
                continue
G
Gyuri Im 已提交
2144 2145
            self.keras_model.add_loss(
                tf.reduce_mean(layer.output, keep_dims=True))
W
Waleed Abdulla 已提交
2146 2147

        # Add L2 Regularization
2148
        # Skip gamma and beta weights of batch normalization layers.
2149
        reg_losses = [keras.regularizers.l2(self.config.WEIGHT_DECAY)(w) / tf.cast(tf.size(w), tf.float32)
2150 2151
                      for w in self.keras_model.trainable_weights
                      if 'gamma' not in w.name and 'beta' not in w.name]
W
Waleed Abdulla 已提交
2152
        self.keras_model.add_loss(tf.add_n(reg_losses))
2153

W
Waleed Abdulla 已提交
2154
        # Compile
G
Gyuri Im 已提交
2155 2156
        self.keras_model.compile(optimizer=optimizer, loss=[
                                 None] * len(self.keras_model.outputs))
W
Waleed Abdulla 已提交
2157

W
Cleanup  
Waleed Abdulla 已提交
2158
        # Add metrics for losses
W
Waleed Abdulla 已提交
2159 2160 2161 2162 2163
        for name in loss_names:
            if name in self.keras_model.metrics_names:
                continue
            layer = self.keras_model.get_layer(name)
            self.keras_model.metrics_names.append(name)
W
Waleed Abdulla 已提交
2164 2165
            self.keras_model.metrics_tensors.append(tf.reduce_mean(
                layer.output, keep_dims=True))
W
Waleed Abdulla 已提交
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185

    def set_trainable(self, layer_regex, keras_model=None, indent=0, verbose=1):
        """Sets model layers as trainable if their names match
        the given regular expression.
        """
        # Print message on the first call (but not on recursive calls)
        if verbose > 0 and keras_model is None:
            log("Selecting layers to train")

        keras_model = keras_model or self.keras_model

        # In multi-GPU training, we wrap the model. Get layers
        # of the inner model because they have the weights.
        layers = keras_model.inner_model.layers if hasattr(keras_model, "inner_model")\
            else keras_model.layers

        for layer in layers:
            # Is the layer a model?
            if layer.__class__.__name__ == 'Model':
                print("In model: ", layer.name)
G
Gyuri Im 已提交
2186 2187
                self.set_trainable(
                    layer_regex, keras_model=layer, indent=indent + 4)
W
Waleed Abdulla 已提交
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
                continue

            if not layer.weights:
                continue
            # Is it trainable?
            trainable = bool(re.fullmatch(layer_regex, layer.name))
            # Update layer. If layer is a container, update inner layer.
            if layer.__class__.__name__ == 'TimeDistributed':
                layer.layer.trainable = trainable
            else:
                layer.trainable = trainable
            # Print trainble layer names
            if trainable and verbose > 0:
                log("{}{:20}   ({})".format(" " * indent, layer.name,
                                            layer.__class__.__name__))

    def set_log_dir(self, model_path=None):
        """Sets the model log directory and epoch counter.

        model_path: If None, or a format different from what this code uses
            then set a new log directory and start epochs from 0. Otherwise,
            extract the log directory and the epoch counter from the file
            name.
        """
        # Set date and epoch counter as if starting a new model
        self.epoch = 0
        now = datetime.datetime.now()

        # If we have a model path with date and epochs use them
        if model_path:
            # Continue from we left of. Get epoch and date from the file name
            # A sample model path might look like:
            # /path/to/logs/coco20171029T2315/mask_rcnn_coco_0001.h5
            regex = r".*/\w+(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/mask\_rcnn\_\w+(\d{4})\.h5"
            m = re.match(regex, model_path)
            if m:
                now = datetime.datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)),
                                        int(m.group(4)), int(m.group(5)))
                self.epoch = int(m.group(6)) + 1

        # Directory for training logs
        self.log_dir = os.path.join(self.model_dir, "{}{:%Y%m%dT%H%M}".format(
            self.config.NAME.lower(), now))

        # Path to save after each epoch. Include placeholders that get filled by Keras.
        self.checkpoint_path = os.path.join(self.log_dir, "mask_rcnn_{}_*epoch*.h5".format(
            self.config.NAME.lower()))
G
Gyuri Im 已提交
2235 2236
        self.checkpoint_path = self.checkpoint_path.replace(
            "*epoch*", "{epoch:04d}")
W
Waleed Abdulla 已提交
2237

W
Waleed Abdulla 已提交
2238 2239
    def train(self, train_dataset, val_dataset, learning_rate, epochs, layers,
              augmentation=None):
W
Waleed Abdulla 已提交
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
        """Train the model.
        train_dataset, val_dataset: Training and validation Dataset objects.
        learning_rate: The learning rate to train with
        epochs: Number of training epochs. Note that previous training epochs
                are considered to be done alreay, so this actually determines
                the epochs to train in total rather than in this particaular
                call.
        layers: Allows selecting wich layers to train. It can be:
            - A regular expression to match layer names to train
            - One of these predefined values:
              heaads: The RPN, classifier and mask heads of the network
              all: All the layers
              3+: Train Resnet stage 3 and up
              4+: Train Resnet stage 4 and up
              5+: Train Resnet stage 5 and up
W
Waleed Abdulla 已提交
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
        augmentation: Optional. An imgaug (https://github.com/aleju/imgaug)
            augmentation. For example, passing imgaug.augmenters.Fliplr(0.5)
            flips images right/left 50% of the time. You can pass complex
            augmentations as well. This augmentation applies 50% of the
            time, and when it does it flips images right/left half the time
            and adds a Gausssian blur with a random sigma in range 0 to 5.

                augmentation = imgaug.augmenters.Sometimes(0.5, [
                    imgaug.augmenters.Fliplr(0.5),
                    imgaug.augmenters.GaussianBlur(sigma=(0.0, 5.0))
                ])
W
Waleed Abdulla 已提交
2266 2267 2268 2269 2270 2271 2272
        """
        assert self.mode == "training", "Create model in training mode."

        # Pre-defined layer regular expressions
        layer_regex = {
            # all layers but the backbone
            "heads": r"(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)",
W
Waleed Abdulla 已提交
2273
            # From a specific Resnet stage and up
W
Waleed Abdulla 已提交
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
            "3+": r"(res3.*)|(bn3.*)|(res4.*)|(bn4.*)|(res5.*)|(bn5.*)|(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)",
            "4+": r"(res4.*)|(bn4.*)|(res5.*)|(bn5.*)|(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)",
            "5+": r"(res5.*)|(bn5.*)|(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)",
            # All layers
            "all": ".*",
        }
        if layers in layer_regex.keys():
            layers = layer_regex[layers]

        # Data generators
G
Gyuri Im 已提交
2284
        train_generator = data_generator(train_dataset, self.config, shuffle=True,
W
Waleed Abdulla 已提交
2285
                                         augmentation=augmentation,
G
Gyuri Im 已提交
2286 2287
                                         batch_size=self.config.BATCH_SIZE)
        val_generator = data_generator(val_dataset, self.config, shuffle=True,
W
Waleed Abdulla 已提交
2288
                                       batch_size=self.config.BATCH_SIZE)
W
Waleed Abdulla 已提交
2289 2290 2291 2292 2293 2294 2295 2296

        # Callbacks
        callbacks = [
            keras.callbacks.TensorBoard(log_dir=self.log_dir,
                                        histogram_freq=0, write_graph=True, write_images=False),
            keras.callbacks.ModelCheckpoint(self.checkpoint_path,
                                            verbose=0, save_weights_only=True),
        ]
G
Gyuri Im 已提交
2297

W
Waleed Abdulla 已提交
2298 2299 2300 2301 2302 2303
        # Train
        log("\nStarting at epoch {}. LR={}\n".format(self.epoch, learning_rate))
        log("Checkpoint Path: {}".format(self.checkpoint_path))
        self.set_trainable(layers)
        self.compile(learning_rate, self.config.LEARNING_MOMENTUM)

2304 2305 2306
        # Work-around for Windows: Keras fails on Windows when using
        # multiprocessing workers. See discussion here:
        # https://github.com/matterport/Mask_RCNN/issues/13#issuecomment-353124009
2307 2308 2309
        if os.name is 'nt':
            workers = 0
        else:
W
Waleed Abdulla 已提交
2310
            workers = multiprocessing.cpu_count()
2311

W
Waleed Abdulla 已提交
2312 2313 2314 2315
        self.keras_model.fit_generator(
            train_generator,
            initial_epoch=self.epoch,
            epochs=epochs,
W
Waleed Abdulla 已提交
2316 2317
            steps_per_epoch=self.config.STEPS_PER_EPOCH,
            callbacks=callbacks,
2318
            validation_data=val_generator,
W
Waleed Abdulla 已提交
2319 2320
            validation_steps=self.config.VALIDATION_STEPS,
            max_queue_size=100,
2321
            workers=workers,
W
Waleed Abdulla 已提交
2322
            use_multiprocessing=True,
G
Gyuri Im 已提交
2323
        )
W
Waleed Abdulla 已提交
2324
        self.epoch = max(self.epoch, epochs)
G
Gyuri Im 已提交
2325

W
Waleed Abdulla 已提交
2326 2327 2328 2329 2330
    def mold_inputs(self, images):
        """Takes a list of images and modifies them to the format expected
        as an input to the neural network.
        images: List of image matricies [height,width,depth]. Images can have
            different sizes.
G
Gyuri Im 已提交
2331

W
Waleed Abdulla 已提交
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
        Returns 3 Numpy matricies:
        molded_images: [N, h, w, 3]. Images resized and normalized.
        image_metas: [N, length of meta data]. Details about each image.
        windows: [N, (y1, x1, y2, x2)]. The portion of the image that has the
            original image (padding excluded).
        """
        molded_images = []
        image_metas = []
        windows = []
        for image in images:
W
Waleed Abdulla 已提交
2342
            # Resize image
W
Waleed Abdulla 已提交
2343 2344 2345 2346 2347
            # TODO: move resizing to mold_image()
            molded_image, window, scale, padding = utils.resize_image(
                image,
                min_dim=self.config.IMAGE_MIN_DIM,
                max_dim=self.config.IMAGE_MAX_DIM,
W
Waleed Abdulla 已提交
2348
                mode=self.config.IMAGE_RESIZE_MODE)
W
Waleed Abdulla 已提交
2349 2350 2351
            molded_image = mold_image(molded_image, self.config)
            # Build image_meta
            image_meta = compose_image_meta(
2352
                0, image.shape, molded_image.shape, window, scale,
W
Waleed Abdulla 已提交
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
                np.zeros([self.config.NUM_CLASSES], dtype=np.int32))
            # Append
            molded_images.append(molded_image)
            windows.append(window)
            image_metas.append(image_meta)
        # Pack into arrays
        molded_images = np.stack(molded_images)
        image_metas = np.stack(image_metas)
        windows = np.stack(windows)
        return molded_images, image_metas, windows

2364 2365
    def unmold_detections(self, detections, mrcnn_mask, original_image_shape,
                          image_shape, window):
W
Waleed Abdulla 已提交
2366 2367 2368 2369
        """Reformats the detections of one image from the format of the neural
        network output to a format suitable for use in the rest of the
        application.

2370
        detections: [N, (y1, x1, y2, x2, class_id, score)] in normalized coordinates
W
Waleed Abdulla 已提交
2371
        mrcnn_mask: [N, height, width, num_classes]
2372 2373 2374 2375
        original_image_shape: [H, W, C] Original image shape before resizing
        image_shape: [H, W, C] Shape of the image after resizing and padding
        window: [y1, x1, y2, x2] Pixel coordinates of box in the image where the real
                image is excluding the padding.
G
Gyuri Im 已提交
2376

W
Waleed Abdulla 已提交
2377 2378 2379 2380 2381 2382 2383 2384
        Returns:
        boxes: [N, (y1, x1, y2, x2)] Bounding boxes in pixels
        class_ids: [N] Integer class IDs for each bounding box
        scores: [N] Float probability scores of the class_id
        masks: [height, width, num_instances] Instance masks
        """
        # How many detections do we have?
        # Detections array is padded with zeros. Find the first class_id == 0.
G
Gyuri Im 已提交
2385
        zero_ix = np.where(detections[:, 4] == 0)[0]
W
Waleed Abdulla 已提交
2386
        N = zero_ix[0] if zero_ix.shape[0] > 0 else detections.shape[0]
G
Gyuri Im 已提交
2387

W
Waleed Abdulla 已提交
2388 2389 2390 2391 2392 2393
        # Extract boxes, class_ids, scores, and class-specific masks
        boxes = detections[:N, :4]
        class_ids = detections[:N, 4].astype(np.int32)
        scores = detections[:N, 5]
        masks = mrcnn_mask[np.arange(N), :, :, class_ids]

2394 2395 2396 2397 2398 2399 2400
        # Translate normalized coordinates in the resized image to pixel
        # coordinates in the original image before resizing
        window = utils.norm_boxes(window, image_shape[:2])
        wy1, wx1, wy2, wx2 = window
        shift = np.array([wy1, wx1, wy1, wx1])
        wh = wy2 - wy1  # window height
        ww = wx2 - wx1  # window width
2401
        scale = np.array([wh, ww, wh, ww])
2402 2403 2404 2405 2406 2407 2408
        # Convert boxes to normalized coordinates on the window
        boxes = np.divide(boxes - shift, scale)
        # Convert boxes to pixel coordinates on the original image
        boxes = utils.denorm_boxes(boxes, original_image_shape[:2])

        # Filter out detections with zero area. Happens in early training when
        # network weights are still random
2409 2410 2411 2412 2413 2414 2415 2416 2417
        exclude_ix = np.where(
            (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) <= 0)[0]
        if exclude_ix.shape[0] > 0:
            boxes = np.delete(boxes, exclude_ix, axis=0)
            class_ids = np.delete(class_ids, exclude_ix, axis=0)
            scores = np.delete(scores, exclude_ix, axis=0)
            masks = np.delete(masks, exclude_ix, axis=0)
            N = class_ids.shape[0]

W
Waleed Abdulla 已提交
2418 2419 2420 2421
        # Resize masks to original image size and set boundary threshold.
        full_masks = []
        for i in range(N):
            # Convert neural network mask to full size mask
2422
            full_mask = utils.unmold_mask(masks[i], boxes[i], original_image_shape)
W
Waleed Abdulla 已提交
2423 2424
            full_masks.append(full_mask)
        full_masks = np.stack(full_masks, axis=-1)\
G
Gyuri Im 已提交
2425 2426
            if full_masks else np.empty((0,) + masks.shape[1:3])

W
Waleed Abdulla 已提交
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
        return boxes, class_ids, scores, full_masks

    def detect(self, images, verbose=0):
        """Runs the detection pipeline.

        images: List of images, potentially of different sizes.

        Returns a list of dicts, one dict per image. The dict contains:
        rois: [N, (y1, x1, y2, x2)] detection bounding boxes
        class_ids: [N] int class IDs
        scores: [N] float probability scores for the class IDs
        masks: [H, W, N] instance binary masks
        """
        assert self.mode == "inference", "Create model in inference mode."
G
Gyuri Im 已提交
2441 2442
        assert len(
            images) == self.config.BATCH_SIZE, "len(images) must be equal to BATCH_SIZE"
W
Waleed Abdulla 已提交
2443

G
Gyuri Im 已提交
2444
        if verbose:
W
Waleed Abdulla 已提交
2445 2446 2447
            log("Processing {} images".format(len(images)))
            for image in images:
                log("image", image)
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464

        # Validate image sizes
        if self.config.IMAGE_RESIZE_MODE == "square":
            image_shape = self.config.IMAGE_SHAPE
        else:
            # All images MUST be of the same size
            image_shape = images[0].shape
            for g in images[1:]:
                assert g.shape == image_shape,\
                    "Images must have the same size unless IMAGE_RESIZE_MODE is 'square'"

        # Anchors
        anchors = self.get_anchors(image_shape)
        # Duplicate across the batch dimension because Keras requires it
        # TODO: can this be optimized to avoid duplicating the anchors?
        anchors = np.broadcast_to(anchors, (self.config.BATCH_SIZE,) + anchors.shape)

W
Waleed Abdulla 已提交
2465 2466 2467 2468 2469
        # Mold inputs to format expected by the neural network
        molded_images, image_metas, windows = self.mold_inputs(images)
        if verbose:
            log("molded_images", molded_images)
            log("image_metas", image_metas)
2470
            log("anchors", anchors)
W
Waleed Abdulla 已提交
2471
        # Run object detection
2472 2473
        detections, _, _, mrcnn_mask, _, _, _ =\
            self.keras_model.predict([molded_images, image_metas, anchors], verbose=0)
W
Waleed Abdulla 已提交
2474 2475 2476 2477 2478
        # Process detections
        results = []
        for i, image in enumerate(images):
            final_rois, final_class_ids, final_scores, final_masks =\
                self.unmold_detections(detections[i], mrcnn_mask[i],
2479 2480
                                       image.shape, molded_images[i].shape,
                                       windows[i])
W
Waleed Abdulla 已提交
2481 2482 2483 2484 2485 2486 2487 2488
            results.append({
                "rois": final_rois,
                "class_ids": final_class_ids,
                "scores": final_scores,
                "masks": final_masks,
            })
        return results

2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
    def get_anchors(self, image_shape):
        """Returns anchor pyramid for the given image size."""
        backbone_shapes = compute_backbone_shapes(self.config, image_shape)
        # Cache anchors and reuse if image shape is the same
        if not hasattr(self, "_anchor_cache"):
            self._anchor_cache = {}
        if not tuple(image_shape) in self._anchor_cache:
            # Generate Anchors
            a = utils.generate_pyramid_anchors(
                self.config.RPN_ANCHOR_SCALES,
                self.config.RPN_ANCHOR_RATIOS,
                backbone_shapes,
                self.config.BACKBONE_STRIDES,
                self.config.RPN_ANCHOR_STRIDE)
            # Keep a copy of the latest anchors in pixel coordinates because
            # it's used in inspect_model notebooks.
            # TODO: Remove this after the notebook are refactored to not use it
            self.anchors = a
            # Normalize coordinates
            self._anchor_cache[tuple(image_shape)] = utils.norm_boxes(a, image_shape[:2])
        return self._anchor_cache[tuple(image_shape)]

W
Waleed Abdulla 已提交
2511 2512 2513 2514
    def ancestor(self, tensor, name, checked=None):
        """Finds the ancestor of a TF tensor in the computation graph.
        tensor: TensorFlow symbolic tensor.
        name: Name of ancestor tensor to find
G
Gyuri Im 已提交
2515
        checked: For internal use. A list of tensors that were already
W
Waleed Abdulla 已提交
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
                 searched to avoid loops in traversing the graph.
        """
        checked = checked if checked is not None else []
        # Put a limit on how deep we go to avoid very long loops
        if len(checked) > 500:
            return None
        # Convert name to a regex and allow matching a number prefix
        # because Keras adds them automatically
        if isinstance(name, str):
            name = re.compile(name.replace("/", r"(\_\d+)*/"))
G
Gyuri Im 已提交
2526

W
Waleed Abdulla 已提交
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
        parents = tensor.op.inputs
        for p in parents:
            if p in checked:
                continue
            if bool(re.fullmatch(name, p.name)):
                return p
            checked.append(p)
            a = self.ancestor(p, name, checked)
            if a is not None:
                return a
        return None

    def find_trainable_layer(self, layer):
        """If a layer is encapsulated by another layer, this function
        digs through the encapsulation and returns the layer that holds
        the weights.
        """
        if layer.__class__.__name__ == 'TimeDistributed':
            return self.find_trainable_layer(layer.layer)
        return layer

    def get_trainable_layers(self):
        """Returns a list of layers that have weights."""
        layers = []
        # Loop through all layers
        for l in self.keras_model.layers:
            # If layer is a wrapper, find inner trainable layer
            l = self.find_trainable_layer(l)
            # Include layer if it has weights
            if l.get_weights():
                layers.append(l)
        return layers
G
Gyuri Im 已提交
2559

W
Waleed Abdulla 已提交
2560 2561 2562 2563
    def run_graph(self, images, outputs):
        """Runs a sub-set of the computation graph that computes the given
        outputs.

G
Gyuri Im 已提交
2564
        outputs: List of tuples (name, tensor) to compute. The tensors are
W
Waleed Abdulla 已提交
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
            symbolic TensorFlow tensors and the names are for easy tracking.

        Returns an ordered dict of results. Keys are the names received in the
        input and values are Numpy arrays.
        """
        model = self.keras_model

        # Organize desired outputs into an ordered dict
        outputs = OrderedDict(outputs)
        for o in outputs.values():
            assert o is not None

        # Build a Keras function to run parts of the computation graph
        inputs = model.inputs
        if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
            inputs += [K.learning_phase()]
        kf = K.function(model.inputs, list(outputs.values()))

        # Run inference
        molded_images, image_metas, windows = self.mold_inputs(images)
        # TODO: support training mode?
        # if TEST_MODE == "training":
G
Gyuri Im 已提交
2587 2588
        #     model_in = [molded_images, image_metas,
        #                 target_rpn_match, target_rpn_bbox,
W
Waleed Abdulla 已提交
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
        #                 gt_boxes, gt_masks]
        #     if not config.USE_RPN_ROIS:
        #         model_in.append(target_rois)
        #     if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
        #         model_in.append(1.)
        #     outputs_np = kf(model_in)
        # else:

        model_in = [molded_images, image_metas]
        if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
            model_in.append(0.)
        outputs_np = kf(model_in)

        # Pack the generated Numpy arrays into a a dict and log the results.
G
Gyuri Im 已提交
2603 2604
        outputs_np = OrderedDict([(k, v)
                                  for k, v in zip(outputs.keys(), outputs_np)])
W
Waleed Abdulla 已提交
2605 2606 2607 2608 2609 2610 2611 2612 2613
        for k, v in outputs_np.items():
            log(k, v)
        return outputs_np


############################################################
#  Data Formatting
############################################################

2614 2615
def compose_image_meta(image_id, original_image_shape, image_shape,
                       window, scale, active_class_ids):
2616
    """Takes attributes of an image and puts them in one 1D array.
G
Gyuri Im 已提交
2617

W
Waleed Abdulla 已提交
2618
    image_id: An int ID of the image. Useful for debugging.
2619 2620
    original_image_shape: [H, W, C] before resizing or padding.
    image_shape: [H, W, C] after resizing and padding
W
Waleed Abdulla 已提交
2621 2622
    window: (y1, x1, y2, x2) in pixels. The area of the image where the real
            image is (excluding the padding)
2623
    scale: The scaling factor applied to the original image (float32)
W
Waleed Abdulla 已提交
2624 2625 2626 2627 2628
    active_class_ids: List of class_ids available in the dataset from which
        the image came. Useful if training on images from multiple datasets
        where not all classes are present in all datasets.
    """
    meta = np.array(
2629 2630 2631 2632 2633 2634
        [image_id] +                  # size=1
        list(original_image_shape) +  # size=3
        list(image_shape) +           # size=3
        list(window) +                # size=4 (y1, x1, y2, x2) in image cooredinates
        [scale] +                     # size=1
        list(active_class_ids)        # size=num_classes
W
Waleed Abdulla 已提交
2635 2636 2637
    )
    return meta

2638

S
Shenoy 已提交
2639 2640
def parse_image_meta_graph(meta):
    """Parses a tensor that contains image attributes to its components.
W
Waleed Abdulla 已提交
2641
    See compose_image_meta() for more details.
S
Shenoy 已提交
2642 2643

    meta: [batch, meta length] where meta length depends on NUM_CLASSES
2644 2645

    Returns a dict of the parsed tensors.
W
Waleed Abdulla 已提交
2646 2647
    """
    image_id = meta[:, 0]
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
    original_image_shape = meta[:, 1:4]
    image_shape = meta[:, 4:7]
    window = meta[:, 7:11]  # (y1, x1, y2, x2) window of image in in pixels
    scale = meta[:, 11]
    active_class_ids = meta[:, 12:]
    return {
        "image_id": image_id,
        "original_image_shape": original_image_shape,
        "image_shape": image_shape,
        "window": window,
        "scale": scale,
        "active_class_ids": active_class_ids,
    }
W
Waleed Abdulla 已提交
2661

2662

W
Waleed Abdulla 已提交
2663
def mold_image(images, config):
2664
    """Expects an RGB image (or array of images) and subtraces
W
Waleed Abdulla 已提交
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
    the mean pixel and converts it to float. Expects image
    colors in RGB order.
    """
    return images.astype(np.float32) - config.MEAN_PIXEL


def unmold_image(normalized_images, config):
    """Takes a image normalized with mold() and returns the original."""
    return (normalized_images + config.MEAN_PIXEL).astype(np.uint8)


############################################################
#  Miscellenous Graph Functions
############################################################

W
Waleed Abdulla 已提交
2680
def trim_zeros_graph(boxes, name=None):
W
Waleed Abdulla 已提交
2681 2682 2683 2684
    """Often boxes are represented with matricies of shape [N, 4] and
    are padded with zeros. This removes zero boxes.

    boxes: [N, 4] matrix of boxes.
W
Waleed Abdulla 已提交
2685
    non_zeros: [N] a 1D boolean mask identifying the rows to keep
W
Waleed Abdulla 已提交
2686
    """
W
Waleed Abdulla 已提交
2687 2688 2689
    non_zeros = tf.cast(tf.reduce_sum(tf.abs(boxes), axis=1), tf.bool)
    boxes = tf.boolean_mask(boxes, non_zeros, name=name)
    return boxes, non_zeros
W
Waleed Abdulla 已提交
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699


def batch_pack_graph(x, counts, num_rows):
    """Picks different number of values from each row
    in x depending on the values in counts.
    """
    outputs = []
    for i in range(num_rows):
        outputs.append(x[i, :counts[i]])
    return tf.concat(outputs, axis=0)
2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733


def norm_boxes_graph(boxes, shape):
    """Converts boxes from pixel coordinates to normalized coordinates.
    boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
    shape: [..., (height, width)] in pixels

    Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
    coordinates it's inside the box.

    Returns:
        [..., (y1, x1, y2, x2)] in normalized coordinates
    """
    h, w = tf.split(tf.cast(shape, tf.float32), 2)
    scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
    shift = tf.constant([0., 0., 1., 1.])
    return tf.divide(boxes - shift, scale)


def denorm_boxes_graph(boxes, shape):
    """Converts boxes from normalized coordinates to pixel coordinates.
    boxes: [..., (y1, x1, y2, x2)] in normalized coordinates
    shape: [..., (height, width)] in pixels

    Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
    coordinates it's inside the box.

    Returns:
        [..., (y1, x1, y2, x2)] in pixel coordinates
    """
    h, w = tf.split(tf.cast(shape, tf.float32), 2)
    scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
    shift = tf.constant([0., 0., 1., 1.])
    return tf.cast(tf.round(tf.multiply(boxes, scale) + shift), tf.int32)