fcn.py 7.82 KB
Newer Older
Zhang's avatar
v0.4.2  
Zhang committed
1
2
3
4
5
6
7
8
9
10
###########################################################################
# Created by: Hang Zhang 
# Email: zhang.hang@rutgers.edu 
# Copyright (c) 2017
###########################################################################
from __future__ import division
import os
import numpy as np
import torch
import torch.nn as nn
Hang Zhang's avatar
Hang Zhang committed
11
from torch.nn.functional import interpolate
Hang Zhang's avatar
Hang Zhang committed
12
from ...nn import ConcurrentModule, SyncBatchNorm
Zhang's avatar
v0.4.2  
Zhang committed
13
14
15

from .base import BaseNet

16
__all__ = ['FCN', 'get_fcn', 'get_fcn_resnet50_pcontext', 'get_fcn_resnet50_ade',
Hang Zhang's avatar
Hang Zhang committed
17
           'get_fcn_resnest50_ade', 'get_fcn_resnest50_pcontext']
Zhang's avatar
v0.4.2  
Zhang committed
18
19
20
21
22
23
24
25
26

class FCN(BaseNet):
    r"""Fully Convolutional Networks for Semantic Segmentation

    Parameters
    ----------
    nclass : int
        Number of categories for the training dataset.
    backbone : string
Hang Zhang's avatar
Hang Zhang committed
27
28
        Pre-trained dilated backbone network type (default:'resnet50s'; 'resnet50s',
        'resnet101s' or 'resnet152s').
Zhang's avatar
v0.4.2  
Zhang committed
29
30
31
32
33
34
35
36
37
38
39
    norm_layer : object
        Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`;


    Reference:

        Long, Jonathan, Evan Shelhamer, and Trevor Darrell. "Fully convolutional networks
        for semantic segmentation." *CVPR*, 2015

    Examples
    --------
Hang Zhang's avatar
Hang Zhang committed
40
    >>> model = FCN(nclass=21, backbone='resnet50s')
Zhang's avatar
v0.4.2  
Zhang committed
41
42
    >>> print(model)
    """
Hang Zhang's avatar
Hang Zhang committed
43
    def __init__(self, nclass, backbone, aux=True, se_loss=False, with_global=False,
Hang Zhang's avatar
Hang Zhang committed
44
45
46
                 norm_layer=SyncBatchNorm, *args, **kwargs):
        super(FCN, self).__init__(nclass, backbone, aux, se_loss, norm_layer=norm_layer,
                                  *args, **kwargs)
Hang Zhang's avatar
Hang Zhang committed
47
        self.head = FCNHead(2048, nclass, norm_layer, self._up_kwargs, with_global)
Zhang's avatar
v0.4.2  
Zhang committed
48
49
50
51
52
53
54
55
        if aux:
            self.auxlayer = FCNHead(1024, nclass, norm_layer)

    def forward(self, x):
        imsize = x.size()[2:]
        _, _, c3, c4 = self.base_forward(x)

        x = self.head(c4)
Hang Zhang's avatar
Hang Zhang committed
56
        x = interpolate(x, imsize, **self._up_kwargs)
Zhang's avatar
v0.4.2  
Zhang committed
57
58
59
        outputs = [x]
        if self.aux:
            auxout = self.auxlayer(c3)
Hang Zhang's avatar
Hang Zhang committed
60
            auxout = interpolate(auxout, imsize, **self._up_kwargs)
Zhang's avatar
v0.4.2  
Zhang committed
61
62
63
            outputs.append(auxout)
        return tuple(outputs)

Hang Zhang's avatar
Hang Zhang committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

class Identity(nn.Module):
    def __init__(self):
        super(Identity, self).__init__()

    def forward(self, x):
        return x

class GlobalPooling(nn.Module):
    def __init__(self, in_channels, out_channels, norm_layer, up_kwargs):
        super(GlobalPooling, self).__init__()
        self._up_kwargs = up_kwargs
        self.gap = nn.Sequential(nn.AdaptiveAvgPool2d(1),
                                 nn.Conv2d(in_channels, out_channels, 1, bias=False),
                                 norm_layer(out_channels),
                                 nn.ReLU(True))

    def forward(self, x):
        _, _, h, w = x.size()
        pool = self.gap(x)
        return interpolate(pool, (h,w), **self._up_kwargs)

Zhang's avatar
v0.4.2  
Zhang committed
86
87
        
class FCNHead(nn.Module):
Hang Zhang's avatar
Hang Zhang committed
88
    def __init__(self, in_channels, out_channels, norm_layer, up_kwargs={}, with_global=False):
Zhang's avatar
v0.4.2  
Zhang committed
89
90
        super(FCNHead, self).__init__()
        inter_channels = in_channels // 4
Hang Zhang's avatar
Hang Zhang committed
91
92
93
94
95
96
97
98
99
100
        self._up_kwargs = up_kwargs
        if with_global:
            self.conv5 = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
                                       norm_layer(inter_channels),
                                       nn.ReLU(),
                                       ConcurrentModule([
                                            Identity(),
                                            GlobalPooling(inter_channels, inter_channels,
                                                          norm_layer, self._up_kwargs),
                                       ]),
101
                                       nn.Dropout(0.1, False),
Hang Zhang's avatar
Hang Zhang committed
102
103
104
105
106
                                       nn.Conv2d(2*inter_channels, out_channels, 1))
        else:
            self.conv5 = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
                                       norm_layer(inter_channels),
                                       nn.ReLU(),
107
                                       nn.Dropout(0.1, False),
Hang Zhang's avatar
Hang Zhang committed
108
                                       nn.Conv2d(inter_channels, out_channels, 1))
Zhang's avatar
v0.4.2  
Zhang committed
109
110
111
112
113

    def forward(self, x):
        return self.conv5(x)


Hang Zhang's avatar
Hang Zhang committed
114
def get_fcn(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
Zhang's avatar
v0.4.2  
Zhang committed
115
116
117
118
119
120
121
122
123
124
125
126
127
            root='~/.encoding/models', **kwargs):
    r"""FCN model from the paper `"Fully Convolutional Network for semantic segmentation"
    <https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf>`_
    Parameters
    ----------
    dataset : str, default pascal_voc
        The dataset that model pretrained on. (pascal_voc, ade20k)
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.
    Examples
    --------
Hang Zhang's avatar
Hang Zhang committed
128
    >>> model = get_fcn(dataset='pascal_voc', backbone='resnet50s', pretrained=False)
Zhang's avatar
v0.4.2  
Zhang committed
129
130
131
    >>> print(model)
    """
    # infer number of classes
Hang Zhang's avatar
Hang Zhang committed
132
    from ...datasets import datasets, acronyms
Hang Zhang's avatar
Hang Zhang committed
133
    model = FCN(datasets[dataset.lower()].NUM_CLASS, backbone=backbone, root=root, **kwargs)
Zhang's avatar
v0.4.2  
Zhang committed
134
    if pretrained:
Hang Zhang's avatar
Hang Zhang committed
135
        from ..model_store import get_model_file
Zhang's avatar
v0.4.2  
Zhang committed
136
        model.load_state_dict(torch.load(
Hang Zhang's avatar
Hang Zhang committed
137
            get_model_file('fcn_%s_%s'%(backbone, acronyms[dataset]), root=root)))
Zhang's avatar
v0.4.2  
Zhang committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    return model

def get_fcn_resnet50_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_fcn_resnet50_pcontext(pretrained=True)
    >>> print(model)
    """
Hang Zhang's avatar
Hang Zhang committed
157
    return get_fcn('pcontext', 'resnet50s', pretrained, root=root, aux=False, **kwargs)
Zhang's avatar
v0.4.2  
Zhang committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

def get_fcn_resnet50_ade(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_fcn_resnet50_ade(pretrained=True)
    >>> print(model)
    """
Hang Zhang's avatar
Hang Zhang committed
176
    return get_fcn('ade20k', 'resnet50s', pretrained, root=root, **kwargs)
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

def get_fcn_resnest50_ade(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_fcn_resnet50_ade(pretrained=True)
    >>> print(model)
    """
    kwargs['aux'] = True
    return get_fcn('ade20k', 'resnest50', pretrained, root=root, **kwargs)
Hang Zhang's avatar
Hang Zhang committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216

def get_fcn_resnest50_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_fcn_resnet50_ade(pretrained=True)
    >>> print(model)
    """
    kwargs['aux'] = True
    return get_fcn('pcontext', 'resnest50', pretrained, root=root, **kwargs)