lanenet.py 20.2 KB
Newer Older
L
LielinJiang 已提交
1
# coding: utf8
W
wuyefeilin 已提交
2
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
L
LielinJiang 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import division
from __future__ import print_function

import paddle.fluid as fluid

from utils.config import cfg
L
LielinJiang 已提交
22 23 24 25 26
from pdseg.models.libs.model_libs import scope, name_scope
from pdseg.models.libs.model_libs import bn, bn_relu, relu
from pdseg.models.libs.model_libs import conv, max_pool, deconv
from pdseg.models.backbone.vgg import VGGNet as vgg_backbone
#from models.backbone.vgg import VGGNet as vgg_backbone
L
LielinJiang 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

# Bottleneck type
REGULAR = 1
DOWNSAMPLING = 2
UPSAMPLING = 3
DILATED = 4
ASYMMETRIC = 5


def prelu(x, decoder=False):
    # If decoder, then perform relu else perform prelu
    if decoder:
        return fluid.layers.relu(x)
    return fluid.layers.prelu(x, 'channel')


def iniatial_block(inputs, name_scope='iniatial_block'):
    '''
    The initial block for Enet has 2 branches: The convolution branch and Maxpool branch.
    The conv branch has 13 filters, while the maxpool branch gives 3 channels corresponding to the RGB channels.
    Both output layers are then concatenated to give an output of 16 channels.

    :param inputs(Tensor): A 4D tensor of shape [batch_size, height, width, channels]
    :return net_concatenated(Tensor): a 4D Tensor of new shape [batch_size, height, width, channels]
    '''
    # Convolutional branch
    with scope(name_scope):
        net_conv = conv(inputs, 13, 3, stride=2, padding=1)
        net_conv = bn(net_conv)
        net_conv = fluid.layers.prelu(net_conv, 'channel')

        # Max pool branch
        net_pool = max_pool(inputs, [2, 2], stride=2, padding='SAME')

        # Concatenated output - does it matter max pool comes first or conv comes first? probably not.
        net_concatenated = fluid.layers.concat([net_conv, net_pool], axis=1)
    return net_concatenated


def bottleneck(inputs,
               output_depth,
               filter_size,
               regularizer_prob,
               projection_ratio=4,
               type=REGULAR,
               seed=0,
               output_shape=None,
               dilation_rate=None,
               decoder=False,
               name_scope='bottleneck'):

    # Calculate the depth reduction based on the projection ratio used in 1x1 convolution.
    reduced_depth = int(inputs.shape[1] / projection_ratio)

    # DOWNSAMPLING BOTTLENECK
    if type == DOWNSAMPLING:
        #=============MAIN BRANCH=============
        #Just perform a max pooling
        with scope('down_sample'):
            inputs_shape = inputs.shape
            with scope('main_max_pool'):
W
wuyefeilin 已提交
88 89 90 91 92 93
                net_main = fluid.layers.conv2d(
                    inputs,
                    inputs_shape[1],
                    filter_size=3,
                    stride=2,
                    padding='SAME')
L
LielinJiang 已提交
94 95 96 97 98 99 100 101

            #First get the difference in depth to pad, then pad with zeros only on the last dimension.
            depth_to_pad = abs(inputs_shape[1] - output_depth)
            paddings = [0, 0, 0, depth_to_pad, 0, 0, 0, 0]
            with scope('main_padding'):
                net_main = fluid.layers.pad(net_main, paddings=paddings)

            with scope('block1'):
W
wuyefeilin 已提交
102 103
                net = conv(
                    inputs, reduced_depth, [2, 2], stride=2, padding='same')
L
LielinJiang 已提交
104 105 106 107
                net = bn(net)
                net = prelu(net, decoder=decoder)

            with scope('block2'):
W
wuyefeilin 已提交
108 109 110 111
                net = conv(
                    net,
                    reduced_depth, [filter_size, filter_size],
                    padding='same')
L
LielinJiang 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
                net = bn(net)
                net = prelu(net, decoder=decoder)

            with scope('block3'):
                net = conv(net, output_depth, [1, 1], padding='same')
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Regularizer
            net = fluid.layers.dropout(net, regularizer_prob, seed=seed)

            # Finally, combine the two branches together via an element-wise addition
            net = fluid.layers.elementwise_add(net, net_main)
            net = prelu(net, decoder=decoder)

        return net, inputs_shape

    # DILATION CONVOLUTION BOTTLENECK
    # Everything is the same as a regular bottleneck except for the dilation rate argument
    elif type == DILATED:
        #Check if dilation rate is given
        if not dilation_rate:
            raise ValueError('Dilation rate is not given.')

        with scope('dilated'):
            # Save the main branch for addition later
            net_main = inputs

            # First projection with 1x1 kernel (dimensionality reduction)
            with scope('block1'):
                net = conv(inputs, reduced_depth, [1, 1])
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Second conv block --- apply dilated convolution here
            with scope('block2'):
W
wuyefeilin 已提交
148 149 150 151 152 153
                net = conv(
                    net,
                    reduced_depth,
                    filter_size,
                    padding='SAME',
                    dilation=dilation_rate)
L
LielinJiang 已提交
154 155 156 157 158
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Final projection with 1x1 kernel (Expansion)
            with scope('block3'):
W
wuyefeilin 已提交
159
                net = conv(net, output_depth, [1, 1])
L
LielinJiang 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Regularizer
            net = fluid.layers.dropout(net, regularizer_prob, seed=seed)
            net = prelu(net, decoder=decoder)

            # Add the main branch
            net = fluid.layers.elementwise_add(net_main, net)
            net = prelu(net, decoder=decoder)

        return net

    # ASYMMETRIC CONVOLUTION BOTTLENECK
    # Everything is the same as a regular bottleneck except for a [5,5] kernel decomposed into two [5,1] then [1,5]
    elif type == ASYMMETRIC:
        # Save the main branch for addition later
        with scope('asymmetric'):
            net_main = inputs
            # First projection with 1x1 kernel (dimensionality reduction)
            with scope('block1'):
                net = conv(inputs, reduced_depth, [1, 1])
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Second conv block --- apply asymmetric conv here
            with scope('block2'):
                with scope('asymmetric_conv2a'):
W
wuyefeilin 已提交
188 189
                    net = conv(
                        net, reduced_depth, [filter_size, 1], padding='same')
L
LielinJiang 已提交
190
                with scope('asymmetric_conv2b'):
W
wuyefeilin 已提交
191 192
                    net = conv(
                        net, reduced_depth, [1, filter_size], padding='same')
L
LielinJiang 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Final projection with 1x1 kernel
            with scope('block3'):
                net = conv(net, output_depth, [1, 1])
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Regularizer
            net = fluid.layers.dropout(net, regularizer_prob, seed=seed)
            net = prelu(net, decoder=decoder)

            # Add the main branch
            net = fluid.layers.elementwise_add(net_main, net)
            net = prelu(net, decoder=decoder)

        return net

    # UPSAMPLING BOTTLENECK
    # Everything is the same as a regular one, except convolution becomes transposed.
    elif type == UPSAMPLING:
        #Check if pooling indices is given

        #Check output_shape given or not
        if output_shape is None:
            raise ValueError('Output depth is not given')

        #=======MAIN BRANCH=======
        #Main branch to upsample. output shape must match with the shape of the layer that was pooled initially, in order
        #for the pooling indices to work correctly. However, the initial pooled layer was padded, so need to reduce dimension
        #before unpooling. In the paper, padding is replaced with convolution for this purpose of reducing the depth!
        with scope('upsampling'):
            with scope('unpool'):
                net_unpool = conv(inputs, output_depth, [1, 1])
                net_unpool = bn(net_unpool)
W
wuyefeilin 已提交
229 230
                net_unpool = fluid.layers.resize_bilinear(
                    net_unpool, out_shape=output_shape[2:])
L
LielinJiang 已提交
231 232 233 234 235 236 237 238

            # First 1x1 projection to reduce depth
            with scope('block1'):
                net = conv(inputs, reduced_depth, [1, 1])
                net = bn(net)
                net = prelu(net, decoder=decoder)

            with scope('block2'):
W
wuyefeilin 已提交
239 240 241 242 243 244
                net = deconv(
                    net,
                    reduced_depth,
                    filter_size=filter_size,
                    stride=2,
                    padding='same')
L
LielinJiang 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Final projection with 1x1 kernel
            with scope('block3'):
                net = conv(net, output_depth, [1, 1])
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Regularizer
            net = fluid.layers.dropout(net, regularizer_prob, seed=seed)
            net = prelu(net, decoder=decoder)

            # Finally, add the unpooling layer and the sub branch together
            net = fluid.layers.elementwise_add(net, net_unpool)
            net = prelu(net, decoder=decoder)

        return net

    # REGULAR BOTTLENECK
    else:
        with scope('regular'):
            net_main = inputs

            # First projection with 1x1 kernel
            with scope('block1'):
                net = conv(inputs, reduced_depth, [1, 1])
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Second conv block
            with scope('block2'):
W
wuyefeilin 已提交
277 278 279 280
                net = conv(
                    net,
                    reduced_depth, [filter_size, filter_size],
                    padding='same')
L
LielinJiang 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Final projection with 1x1 kernel
            with scope('block3'):
                net = conv(net, output_depth, [1, 1])
                net = bn(net)
                net = prelu(net, decoder=decoder)

            # Regularizer
            net = fluid.layers.dropout(net, regularizer_prob, seed=seed)
            net = prelu(net, decoder=decoder)

            # Add the main branch
            net = fluid.layers.elementwise_add(net_main, net)
            net = prelu(net, decoder=decoder)

        return net


def ENet_stage1(inputs, name_scope='stage1_block'):
    with scope(name_scope):
        with scope('bottleneck1_0'):
            net, inputs_shape_1 \
              = bottleneck(inputs, output_depth=64, filter_size=3, regularizer_prob=0.01, type=DOWNSAMPLING,
                           name_scope='bottleneck1_0')
        with scope('bottleneck1_1'):
W
wuyefeilin 已提交
308 309 310 311 312 313
            net = bottleneck(
                net,
                output_depth=64,
                filter_size=3,
                regularizer_prob=0.01,
                name_scope='bottleneck1_1')
L
LielinJiang 已提交
314
        with scope('bottleneck1_2'):
W
wuyefeilin 已提交
315 316 317 318 319 320
            net = bottleneck(
                net,
                output_depth=64,
                filter_size=3,
                regularizer_prob=0.01,
                name_scope='bottleneck1_2')
L
LielinJiang 已提交
321
        with scope('bottleneck1_3'):
W
wuyefeilin 已提交
322 323 324 325 326 327
            net = bottleneck(
                net,
                output_depth=64,
                filter_size=3,
                regularizer_prob=0.01,
                name_scope='bottleneck1_3')
L
LielinJiang 已提交
328
        with scope('bottleneck1_4'):
W
wuyefeilin 已提交
329 330 331 332 333 334
            net = bottleneck(
                net,
                output_depth=64,
                filter_size=3,
                regularizer_prob=0.01,
                name_scope='bottleneck1_4')
L
LielinJiang 已提交
335 336 337 338 339 340 341 342 343 344
    return net, inputs_shape_1


def ENet_stage2(inputs, name_scope='stage2_block'):
    with scope(name_scope):
        net, inputs_shape_2 \
          = bottleneck(inputs, output_depth=128, filter_size=3, regularizer_prob=0.1, type=DOWNSAMPLING,
                       name_scope='bottleneck2_0')
        for i in range(2):
            with scope('bottleneck2_{}'.format(str(4 * i + 1))):
W
wuyefeilin 已提交
345 346 347 348 349 350
                net = bottleneck(
                    net,
                    output_depth=128,
                    filter_size=3,
                    regularizer_prob=0.1,
                    name_scope='bottleneck2_{}'.format(str(4 * i + 1)))
L
LielinJiang 已提交
351
            with scope('bottleneck2_{}'.format(str(4 * i + 2))):
W
wuyefeilin 已提交
352 353 354 355 356 357 358 359
                net = bottleneck(
                    net,
                    output_depth=128,
                    filter_size=3,
                    regularizer_prob=0.1,
                    type=DILATED,
                    dilation_rate=(2**(2 * i + 1)),
                    name_scope='bottleneck2_{}'.format(str(4 * i + 2)))
L
LielinJiang 已提交
360
            with scope('bottleneck2_{}'.format(str(4 * i + 3))):
W
wuyefeilin 已提交
361 362 363 364 365 366 367
                net = bottleneck(
                    net,
                    output_depth=128,
                    filter_size=5,
                    regularizer_prob=0.1,
                    type=ASYMMETRIC,
                    name_scope='bottleneck2_{}'.format(str(4 * i + 3)))
L
LielinJiang 已提交
368
            with scope('bottleneck2_{}'.format(str(4 * i + 4))):
W
wuyefeilin 已提交
369 370 371 372 373 374 375 376
                net = bottleneck(
                    net,
                    output_depth=128,
                    filter_size=3,
                    regularizer_prob=0.1,
                    type=DILATED,
                    dilation_rate=(2**(2 * i + 2)),
                    name_scope='bottleneck2_{}'.format(str(4 * i + 4)))
L
LielinJiang 已提交
377 378 379 380 381 382 383
    return net, inputs_shape_2


def ENet_stage3(inputs, name_scope='stage3_block'):
    with scope(name_scope):
        for i in range(2):
            with scope('bottleneck3_{}'.format(str(4 * i + 0))):
W
wuyefeilin 已提交
384 385 386 387 388 389
                net = bottleneck(
                    inputs,
                    output_depth=128,
                    filter_size=3,
                    regularizer_prob=0.1,
                    name_scope='bottleneck3_{}'.format(str(4 * i + 0)))
L
LielinJiang 已提交
390
            with scope('bottleneck3_{}'.format(str(4 * i + 1))):
W
wuyefeilin 已提交
391 392 393 394 395 396 397 398
                net = bottleneck(
                    net,
                    output_depth=128,
                    filter_size=3,
                    regularizer_prob=0.1,
                    type=DILATED,
                    dilation_rate=(2**(2 * i + 1)),
                    name_scope='bottleneck3_{}'.format(str(4 * i + 1)))
L
LielinJiang 已提交
399
            with scope('bottleneck3_{}'.format(str(4 * i + 2))):
W
wuyefeilin 已提交
400 401 402 403 404 405 406
                net = bottleneck(
                    net,
                    output_depth=128,
                    filter_size=5,
                    regularizer_prob=0.1,
                    type=ASYMMETRIC,
                    name_scope='bottleneck3_{}'.format(str(4 * i + 2)))
L
LielinJiang 已提交
407
            with scope('bottleneck3_{}'.format(str(4 * i + 3))):
W
wuyefeilin 已提交
408 409 410 411 412 413 414 415
                net = bottleneck(
                    net,
                    output_depth=128,
                    filter_size=3,
                    regularizer_prob=0.1,
                    type=DILATED,
                    dilation_rate=(2**(2 * i + 2)),
                    name_scope='bottleneck3_{}'.format(str(4 * i + 3)))
L
LielinJiang 已提交
416 417 418
    return net


W
wuyefeilin 已提交
419 420 421 422 423
def ENet_stage4(inputs,
                inputs_shape,
                connect_tensor,
                skip_connections=True,
                name_scope='stage4_block'):
L
LielinJiang 已提交
424 425
    with scope(name_scope):
        with scope('bottleneck4_0'):
W
wuyefeilin 已提交
426 427 428 429 430 431 432 433 434
            net = bottleneck(
                inputs,
                output_depth=64,
                filter_size=3,
                regularizer_prob=0.1,
                type=UPSAMPLING,
                decoder=True,
                output_shape=inputs_shape,
                name_scope='bottleneck4_0')
L
LielinJiang 已提交
435 436 437 438

        if skip_connections:
            net = fluid.layers.elementwise_add(net, connect_tensor)
        with scope('bottleneck4_1'):
W
wuyefeilin 已提交
439 440 441 442 443 444 445
            net = bottleneck(
                net,
                output_depth=64,
                filter_size=3,
                regularizer_prob=0.1,
                decoder=True,
                name_scope='bottleneck4_1')
L
LielinJiang 已提交
446
        with scope('bottleneck4_2'):
W
wuyefeilin 已提交
447 448 449 450 451 452 453
            net = bottleneck(
                net,
                output_depth=64,
                filter_size=3,
                regularizer_prob=0.1,
                decoder=True,
                name_scope='bottleneck4_2')
L
LielinJiang 已提交
454 455 456 457

    return net


W
wuyefeilin 已提交
458 459 460 461
def ENet_stage5(inputs,
                inputs_shape,
                connect_tensor,
                skip_connections=True,
L
LielinJiang 已提交
462 463
                name_scope='stage5_block'):
    with scope(name_scope):
W
wuyefeilin 已提交
464 465 466 467 468 469 470 471 472
        net = bottleneck(
            inputs,
            output_depth=16,
            filter_size=3,
            regularizer_prob=0.1,
            type=UPSAMPLING,
            decoder=True,
            output_shape=inputs_shape,
            name_scope='bottleneck5_0')
L
LielinJiang 已提交
473 474 475 476

        if skip_connections:
            net = fluid.layers.elementwise_add(net, connect_tensor)
        with scope('bottleneck5_1'):
W
wuyefeilin 已提交
477 478 479 480 481 482 483
            net = bottleneck(
                net,
                output_depth=16,
                filter_size=3,
                regularizer_prob=0.1,
                decoder=True,
                name_scope='bottleneck5_1')
L
LielinJiang 已提交
484 485 486 487 488 489 490 491 492 493 494 495
    return net


def decoder(input, num_classes):

    if 'enet' in cfg.MODEL.LANENET.BACKBONE:
        # Segmentation branch
        with scope('LaneNetSeg'):
            initial, stage1, stage2, inputs_shape_1, inputs_shape_2 = input
            segStage3 = ENet_stage3(stage2)
            segStage4 = ENet_stage4(segStage3, inputs_shape_2, stage1)
            segStage5 = ENet_stage5(segStage4, inputs_shape_1, initial)
W
wuyefeilin 已提交
496 497
            segLogits = deconv(
                segStage5, num_classes, filter_size=2, stride=2, padding='SAME')
L
LielinJiang 已提交
498 499 500 501 502 503

        # Embedding branch
        with scope('LaneNetEm'):
            emStage3 = ENet_stage3(stage2)
            emStage4 = ENet_stage4(emStage3, inputs_shape_2, stage1)
            emStage5 = ENet_stage5(emStage4, inputs_shape_1, initial)
W
wuyefeilin 已提交
504 505
            emLogits = deconv(
                emStage5, 4, filter_size=2, stride=2, padding='SAME')
L
LielinJiang 已提交
506 507 508 509 510 511 512 513 514 515

    elif 'vgg' in cfg.MODEL.LANENET.BACKBONE:
        encoder_list = ['pool5', 'pool4', 'pool3']
        # score stage
        input_tensor = input[encoder_list[0]]
        with scope('score_origin'):
            score = conv(input_tensor, 64, 1)
        encoder_list = encoder_list[1:]
        for i in range(len(encoder_list)):
            with scope('deconv_{:d}'.format(i + 1)):
W
wuyefeilin 已提交
516 517
                deconv_out = deconv(
                    score, 64, filter_size=4, stride=2, padding='SAME')
L
LielinJiang 已提交
518 519 520 521 522 523
            input_tensor = input[encoder_list[i]]
            with scope('score_{:d}'.format(i + 1)):
                score = conv(input_tensor, 64, 1)
            score = fluid.layers.elementwise_add(deconv_out, score)

        with scope('deconv_final'):
W
wuyefeilin 已提交
524 525
            emLogits = deconv(
                score, 64, filter_size=16, stride=8, padding='SAME')
L
LielinJiang 已提交
526 527 528 529 530 531 532 533 534
        with scope('score_final'):
            segLogits = conv(emLogits, num_classes, 1)
        emLogits = relu(conv(emLogits, 4, 1))
    return segLogits, emLogits


def encoder(input):
    if 'vgg' in cfg.MODEL.LANENET.BACKBONE:
        model = vgg_backbone(layers=16)
L
LielinJiang 已提交
535 536
        #output = model.net(input)

W
wuyefeilin 已提交
537 538
        _, encode_feature_dict = model.net(
            input, end_points=13, decode_points=[7, 10, 13])
L
LielinJiang 已提交
539 540 541 542
        output = {}
        output['pool3'] = encode_feature_dict[7]
        output['pool4'] = encode_feature_dict[10]
        output['pool5'] = encode_feature_dict[13]
L
LielinJiang 已提交
543 544 545 546 547 548 549
    elif 'enet' in cfg.MODEL.LANET.BACKBONE:
        with scope('LaneNetBase'):
            initial = iniatial_block(input)
            stage1, inputs_shape_1 = ENet_stage1(initial)
            stage2, inputs_shape_2 = ENet_stage2(stage1)
            output = (initial, stage1, stage2, inputs_shape_1, inputs_shape_2)
    else:
W
wuyefeilin 已提交
550 551 552
        raise Exception(
            "LaneNet expect enet and vgg backbone, but received {}".format(
                cfg.MODEL.LANENET.BACKBONE))
L
LielinJiang 已提交
553 554 555 556 557 558 559 560 561
    return output


def lanenet(img, num_classes):

    output = encoder(img)
    segLogits, emLogits = decoder(output, num_classes)

    return segLogits, emLogits