deeplab.py 15.1 KB
Newer Older
W
wuzewu 已提交
1
# coding: utf8
W
wuyefeilin 已提交
2
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
W
wuzewu 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# 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 absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import paddle
import paddle.fluid as fluid
from utils.config import cfg
from models.libs.model_libs import scope, name_scope
W
wuzewu 已提交
24
from models.libs.model_libs import bn, bn_relu, relu, qsigmoid
W
wuzewu 已提交
25 26
from models.libs.model_libs import conv
from models.libs.model_libs import separate_conv
W
wuzewu 已提交
27 28
from models.backbone.mobilenet_v2 import MobileNetV2 as mobilenet_v2_backbone
from models.backbone.mobilenet_v3 import MobileNetV3 as mobilenet_v3_backbone
W
wuzewu 已提交
29
from models.backbone.xception import Xception as xception_backbone
C
chenguowei01 已提交
30
from models.backbone.resnet_vd import ResNet as resnet_vd_backbone
W
wuzewu 已提交
31

32

W
wuzewu 已提交
33 34 35 36 37 38
def encoder(input):
    # 编码器配置,采用ASPP架构,pooling + 1x1_conv + 三个不同尺度的空洞卷积并行, concat后1x1conv
    # ASPP_WITH_SEP_CONV:默认为真,使用depthwise可分离卷积,否则使用普通卷积
    # OUTPUT_STRIDE: 下采样倍数,8或16,决定aspp_ratios大小
    # aspp_ratios:ASPP模块空洞卷积的采样率

W
wuzewu 已提交
39 40 41 42 43 44 45
    if not cfg.MODEL.DEEPLAB.ENCODER.ASPP_RATIOS:
        if cfg.MODEL.DEEPLAB.OUTPUT_STRIDE == 16:
            aspp_ratios = [6, 12, 18]
        elif cfg.MODEL.DEEPLAB.OUTPUT_STRIDE == 8:
            aspp_ratios = [12, 24, 36]
        else:
            aspp_ratios = []
W
wuzewu 已提交
46
    else:
W
wuzewu 已提交
47
        aspp_ratios = cfg.MODEL.DEEPLAB.ENCODER.ASPP_RATIOS
W
wuzewu 已提交
48 49 50 51 52

    param_attr = fluid.ParamAttr(
        name=name_scope + 'weights',
        regularizer=None,
        initializer=fluid.initializer.TruncatedNormal(loc=0.0, scale=0.06))
W
wuzewu 已提交
53 54

    concat_logits = []
W
wuzewu 已提交
55
    with scope('encoder'):
W
wuzewu 已提交
56
        channel = cfg.MODEL.DEEPLAB.ENCODER.ASPP_CONVS_FILTERS
W
wuzewu 已提交
57
        with scope("image_pool"):
W
wuzewu 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
            if not cfg.MODEL.DEEPLAB.ENCODER.POOLING_CROP_SIZE:
                image_avg = fluid.layers.reduce_mean(
                    input, [2, 3], keep_dim=True)
            else:
                pool_w = int((cfg.MODEL.DEEPLAB.ENCODER.POOLING_CROP_SIZE[0] -
                              1.0) / cfg.MODEL.DEEPLAB.OUTPUT_STRIDE + 1.0)
                pool_h = int((cfg.MODEL.DEEPLAB.ENCODER.POOLING_CROP_SIZE[1] -
                              1.0) / cfg.MODEL.DEEPLAB.OUTPUT_STRIDE + 1.0)
                image_avg = fluid.layers.pool2d(
                    input,
                    pool_size=(pool_h, pool_w),
                    pool_stride=cfg.MODEL.DEEPLAB.ENCODER.POOLING_STRIDE,
                    pool_type='avg',
                    pool_padding='VALID')

            act = qsigmoid if cfg.MODEL.DEEPLAB.ENCODER.SE_USE_QSIGMOID else bn_relu
            image_avg = act(
W
wuzewu 已提交
75 76 77 78 79 80 81 82 83
                conv(
                    image_avg,
                    channel,
                    1,
                    1,
                    groups=1,
                    padding=0,
                    param_attr=param_attr))
            image_avg = fluid.layers.resize_bilinear(image_avg, input.shape[2:])
W
wuzewu 已提交
84 85
            if cfg.MODEL.DEEPLAB.ENCODER.ADD_IMAGE_LEVEL_FEATURE:
                concat_logits.append(image_avg)
86

W
wuzewu 已提交
87 88 89 90 91 92 93 94 95 96
        with scope("aspp0"):
            aspp0 = bn_relu(
                conv(
                    input,
                    channel,
                    1,
                    1,
                    groups=1,
                    padding=0,
                    param_attr=param_attr))
W
wuzewu 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 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 148 149
            concat_logits.append(aspp0)

        if aspp_ratios:
            with scope("aspp1"):
                if cfg.MODEL.DEEPLAB.ASPP_WITH_SEP_CONV:
                    aspp1 = separate_conv(
                        input, channel, 1, 3, dilation=aspp_ratios[0], act=relu)
                else:
                    aspp1 = bn_relu(
                        conv(
                            input,
                            channel,
                            stride=1,
                            filter_size=3,
                            dilation=aspp_ratios[0],
                            padding=aspp_ratios[0],
                            param_attr=param_attr))
                concat_logits.append(aspp1)
            with scope("aspp2"):
                if cfg.MODEL.DEEPLAB.ASPP_WITH_SEP_CONV:
                    aspp2 = separate_conv(
                        input, channel, 1, 3, dilation=aspp_ratios[1], act=relu)
                else:
                    aspp2 = bn_relu(
                        conv(
                            input,
                            channel,
                            stride=1,
                            filter_size=3,
                            dilation=aspp_ratios[1],
                            padding=aspp_ratios[1],
                            param_attr=param_attr))
                concat_logits.append(aspp2)
            with scope("aspp3"):
                if cfg.MODEL.DEEPLAB.ASPP_WITH_SEP_CONV:
                    aspp3 = separate_conv(
                        input, channel, 1, 3, dilation=aspp_ratios[2], act=relu)
                else:
                    aspp3 = bn_relu(
                        conv(
                            input,
                            channel,
                            stride=1,
                            filter_size=3,
                            dilation=aspp_ratios[2],
                            padding=aspp_ratios[2],
                            param_attr=param_attr))
                concat_logits.append(aspp3)

        with scope("concat"):
            data = fluid.layers.concat(concat_logits, axis=1)
            if cfg.MODEL.DEEPLAB.ENCODER.ASPP_WITH_CONCAT_PROJECTION:
                data = bn_relu(
W
wuzewu 已提交
150
                    conv(
W
wuzewu 已提交
151
                        data,
W
wuzewu 已提交
152
                        channel,
W
wuzewu 已提交
153 154 155 156
                        1,
                        1,
                        groups=1,
                        padding=0,
W
wuzewu 已提交
157
                        param_attr=param_attr))
W
wuzewu 已提交
158 159 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 188 189 190 191 192 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
                data = fluid.layers.dropout(data, 0.9)

        if cfg.MODEL.DEEPLAB.ENCODER.ASPP_WITH_SE:
            data = data * image_avg
        return data


def _decoder_with_sum_merge(encode_data, decode_shortcut, param_attr):
    encode_data = fluid.layers.resize_bilinear(encode_data,
                                               decode_shortcut.shape[2:])
    encode_data = conv(
        encode_data,
        cfg.MODEL.DEEPLAB.DECODER.CONV_FILTERS,
        1,
        1,
        groups=1,
        padding=0,
        param_attr=param_attr)

    with scope('merge'):
        decode_shortcut = conv(
            decode_shortcut,
            cfg.MODEL.DEEPLAB.DECODER.CONV_FILTERS,
            1,
            1,
            groups=1,
            padding=0,
            param_attr=param_attr)

        return encode_data + decode_shortcut


def _decoder_with_concat(encode_data, decode_shortcut, param_attr):
    with scope('concat'):
        decode_shortcut = bn_relu(
            conv(
                decode_shortcut,
                48,
                1,
                1,
                groups=1,
                padding=0,
                param_attr=param_attr))

        encode_data = fluid.layers.resize_bilinear(encode_data,
                                                   decode_shortcut.shape[2:])
        encode_data = fluid.layers.concat([encode_data, decode_shortcut],
                                          axis=1)
    if cfg.MODEL.DEEPLAB.DECODER_USE_SEP_CONV:
        with scope("separable_conv1"):
            encode_data = separate_conv(
                encode_data,
                cfg.MODEL.DEEPLAB.DECODER.CONV_FILTERS,
                1,
                3,
                dilation=1,
                act=relu)
        with scope("separable_conv2"):
            encode_data = separate_conv(
                encode_data,
                cfg.MODEL.DEEPLAB.DECODER.CONV_FILTERS,
                1,
                3,
                dilation=1,
                act=relu)
    else:
        with scope("decoder_conv1"):
            encode_data = bn_relu(
W
wuzewu 已提交
226
                conv(
W
wuzewu 已提交
227 228 229 230 231 232
                    encode_data,
                    cfg.MODEL.DEEPLAB.DECODER.CONV_FILTERS,
                    stride=1,
                    filter_size=3,
                    dilation=1,
                    padding=1,
W
wuzewu 已提交
233
                    param_attr=param_attr))
W
wuzewu 已提交
234 235 236 237 238 239 240 241 242 243 244
        with scope("decoder_conv2"):
            encode_data = bn_relu(
                conv(
                    encode_data,
                    cfg.MODEL.DEEPLAB.DECODER.CONV_FILTERS,
                    stride=1,
                    filter_size=3,
                    dilation=1,
                    padding=1,
                    param_attr=param_attr))
    return encode_data
W
wuzewu 已提交
245 246 247 248 249 250 251 252 253 254 255 256


def decoder(encode_data, decode_shortcut):
    # 解码器配置
    # encode_data:编码器输出
    # decode_shortcut: 从backbone引出的分支, resize后与encode_data concat
    # DECODER_USE_SEP_CONV: 默认为真,则concat后连接两个可分离卷积,否则为普通卷积
    param_attr = fluid.ParamAttr(
        name=name_scope + 'weights',
        regularizer=None,
        initializer=fluid.initializer.TruncatedNormal(loc=0.0, scale=0.06))
    with scope('decoder'):
W
wuzewu 已提交
257 258 259
        if cfg.MODEL.DEEPLAB.DECODER.USE_SUM_MERGE:
            return _decoder_with_sum_merge(encode_data, decode_shortcut,
                                           param_attr)
260

W
wuzewu 已提交
261 262 263 264 265 266 267 268
        return _decoder_with_concat(encode_data, decode_shortcut, param_attr)


def mobilenet(input):
    if 'v3' in cfg.MODEL.DEEPLAB.BACKBONE:
        model_name = 'large' if 'large' in cfg.MODEL.DEEPLAB.BACKBONE else 'small'
        return _mobilenetv3(input, model_name)
    return _mobilenetv2(input)
W
wuzewu 已提交
269 270


W
wuzewu 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
def _mobilenetv3(input, model_name='large'):
    # Backbone: mobilenetv3结构配置
    # DEPTH_MULTIPLIER: mobilenetv3的scale设置,默认1.0
    # OUTPUT_STRIDE:下采样倍数
    scale = cfg.MODEL.DEEPLAB.DEPTH_MULTIPLIER
    output_stride = cfg.MODEL.DEEPLAB.OUTPUT_STRIDE
    lr_mult_shortcut = cfg.MODEL.DEEPLAB.BACKBONE_LR_MULT_LIST
    model = mobilenet_v3_backbone(
        scale=scale,
        output_stride=output_stride,
        model_name=model_name,
        lr_mult_list=lr_mult_shortcut)
    data, decode_shortcut = model.net(input)
    return data, decode_shortcut


def _mobilenetv2(input):
W
wuzewu 已提交
288 289 290 291 292
    # Backbone: mobilenetv2结构配置
    # DEPTH_MULTIPLIER: mobilenetv2的scale设置,默认1.0
    # OUTPUT_STRIDE:下采样倍数
    # end_points: mobilenetv2的block数
    # decode_point: 从mobilenetv2中引出分支所在block数, 作为decoder输入
W
wuzewu 已提交
293 294 295 296
    if cfg.MODEL.DEEPLAB.BACKBONE_LR_MULT_LIST is not None:
        print(
            'mobilenetv2 backbone do not support BACKBONE_LR_MULT_LIST setting')

W
wuzewu 已提交
297 298
    scale = cfg.MODEL.DEEPLAB.DEPTH_MULTIPLIER
    output_stride = cfg.MODEL.DEEPLAB.OUTPUT_STRIDE
W
wuzewu 已提交
299
    model = mobilenet_v2_backbone(scale=scale, output_stride=output_stride)
W
wuzewu 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    end_points = 18
    decode_point = 4
    data, decode_shortcuts = model.net(
        input, end_points=end_points, decode_points=decode_point)
    decode_shortcut = decode_shortcuts[decode_point]
    return data, decode_shortcut


def xception(input):
    # Backbone: Xception结构配置, xception_65, xception_41, xception_71三种可选
    # decode_point: 从Xception中引出分支所在block数,作为decoder输入
    # end_point:Xception的block数
    cfg.MODEL.DEFAULT_EPSILON = 1e-3
    model = xception_backbone(cfg.MODEL.DEEPLAB.BACKBONE)
    backbone = cfg.MODEL.DEEPLAB.BACKBONE
    output_stride = cfg.MODEL.DEEPLAB.OUTPUT_STRIDE
    if '65' in backbone:
        decode_point = 2
        end_points = 21
    if '41' in backbone:
        decode_point = 2
        end_points = 13
    if '71' in backbone:
        decode_point = 3
        end_points = 23
    data, decode_shortcuts = model.net(
        input,
        output_stride=output_stride,
        end_points=end_points,
        decode_points=decode_point)
    decode_shortcut = decode_shortcuts[decode_point]
    return data, decode_shortcut


C
chenguowei01 已提交
334
def resnet_vd(input):
C
chenguowei01 已提交
335
    # backbone: resnet_vd, 可选resnet50_vd, resnet101_vd
C
chenguowei01 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    # end_points: resnet终止层数
    # dilation_dict: resnet block数及对应的膨胀卷积尺度
    backbone = cfg.MODEL.DEEPLAB.BACKBONE
    if '50' in backbone:
        layers = 50
    elif '101' in backbone:
        layers = 101
    else:
        raise Exception("resnet_vd backbone only support layers 50 or 101")
    output_stride = cfg.MODEL.DEEPLAB.OUTPUT_STRIDE
    end_points = layers - 1
    decode_point = 10
    if output_stride == 8:
        dilation_dict = {2: 2, 3: 4}
    elif output_stride == 16:
        dilation_dict = {3: 2}
    else:
        raise Exception("deeplab only support stride 8 or 16")
C
chenguowei01 已提交
354
    lr_mult_list = cfg.MODEL.DEEPLAB.BACKBONE_LR_MULT_LIST
C
chenguowei01 已提交
355 356
    if lr_mult_list is None:
        lr_mult_list = [1.0, 1.0, 1.0, 1.0, 1.0]
C
chenguowei01 已提交
357 358
    model = resnet_vd_backbone(
        layers, stem='deeplab', lr_mult_list=lr_mult_list)
C
chenguowei01 已提交
359 360 361 362 363 364 365 366 367 368
    data, decode_shortcuts = model.net(
        input,
        end_points=end_points,
        decode_points=decode_point,
        dilation_dict=dilation_dict)
    decode_shortcut = decode_shortcuts[decode_point]

    return data, decode_shortcut


W
wuzewu 已提交
369 370 371 372
def deeplabv3p(img, num_classes):
    # Backbone设置:xception 或 mobilenetv2
    if 'xception' in cfg.MODEL.DEEPLAB.BACKBONE:
        data, decode_shortcut = xception(img)
C
chenguowei01 已提交
373 374 375 376
        if cfg.MODEL.DEEPLAB.BACKBONE_LR_MULT_LIST is not None:
            print(
                'xception backbone do not support BACKBONE_LR_MULT_LIST setting'
            )
W
wuzewu 已提交
377
    elif 'mobilenet' in cfg.MODEL.DEEPLAB.BACKBONE:
W
wuzewu 已提交
378
        data, decode_shortcut = mobilenet(img)
C
chenguowei01 已提交
379
    elif 'resnet' in cfg.MODEL.DEEPLAB.BACKBONE:
C
update  
chenguowei01 已提交
380
        data, decode_shortcut = resnet_vd(img)
W
wuzewu 已提交
381
    else:
C
chenguowei01 已提交
382
        raise Exception(
C
chenguowei01 已提交
383
            "deeplab only support xception, mobilenet, and resnet_vd backbone")
W
wuzewu 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397

    # 编码器解码器设置
    cfg.MODEL.DEFAULT_EPSILON = 1e-5
    if cfg.MODEL.DEEPLAB.ENCODER_WITH_ASPP:
        data = encoder(data)
    if cfg.MODEL.DEEPLAB.ENABLE_DECODER:
        data = decoder(data, decode_shortcut)

    # 根据类别数设置最后一个卷积层输出,并resize到图片原始尺寸
    param_attr = fluid.ParamAttr(
        name=name_scope + 'weights',
        regularizer=fluid.regularizer.L2DecayRegularizer(
            regularization_coeff=0.0),
        initializer=fluid.initializer.TruncatedNormal(loc=0.0, scale=0.01))
398

W
wuzewu 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
    if not cfg.MODEL.DEEPLAB.DECODER.OUTPUT_IS_LOGITS:
        with scope('logit'):
            with fluid.name_scope('last_conv'):
                logit = conv(
                    data,
                    num_classes,
                    1,
                    stride=1,
                    padding=0,
                    bias_attr=True,
                    param_attr=param_attr)
    else:
        logit = data

    logit = fluid.layers.resize_bilinear(logit, img.shape[2:])
W
wuzewu 已提交
414
    return logit