|
| 1 | +"""DeepLabV3+ with wideresnet backbone for semantic segmentation""" |
| 2 | +# pylint: disable=missing-docstring,arguments-differ,unused-argument |
| 3 | +from mxnet.gluon import nn |
| 4 | +from mxnet.context import cpu |
| 5 | +from mxnet.gluon.nn import HybridBlock |
| 6 | +from .wideresnet import wider_resnet38_a2 |
| 7 | + |
| 8 | +__all__ = ['DeepLabWV3Plus', 'get_deeplabv3b_plus', 'get_deeplab_v3b_plus_wideresnet_citys'] |
| 9 | + |
| 10 | +class DeepLabWV3Plus(HybridBlock): |
| 11 | + r"""DeepLabWV3Plus |
| 12 | +
|
| 13 | + Parameters |
| 14 | + ---------- |
| 15 | + nclass : int |
| 16 | + Number of categories for the training dataset. |
| 17 | + backbone : string |
| 18 | + Pre-trained dilated backbone network type (default:'wideresnet'). |
| 19 | + norm_layer : object |
| 20 | + Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`; |
| 21 | + for Synchronized Cross-GPU BachNormalization). |
| 22 | + aux : bool |
| 23 | + Auxiliary loss. |
| 24 | +
|
| 25 | + Reference: |
| 26 | +
|
| 27 | + Chen, Liang-Chieh, et al. "Encoder-Decoder with Atrous Separable Convolution for Semantic |
| 28 | + Image Segmentation.", https://arxiv.org/abs/1802.02611, ECCV 2018 |
| 29 | + """ |
| 30 | + def __init__(self, nclass, backbone='wideresnet', aux=False, ctx=cpu(), pretrained_base=True, |
| 31 | + height=None, width=None, base_size=520, crop_size=480, dilated=True, **kwargs): |
| 32 | + super(DeepLabWV3Plus, self).__init__() |
| 33 | + |
| 34 | + height = height if height is not None else crop_size |
| 35 | + width = width if width is not None else crop_size |
| 36 | + self._up_kwargs = {'height': height, 'width': width} |
| 37 | + self.base_size = base_size |
| 38 | + self.crop_size = crop_size |
| 39 | + print('self.crop_size', self.crop_size) |
| 40 | + |
| 41 | + with self.name_scope(): |
| 42 | + pretrained = wider_resnet38_a2(classes=1000, dilation=True) |
| 43 | + pretrained.initialize(ctx=ctx) |
| 44 | + self.mod1 = pretrained.mod1 |
| 45 | + self.mod2 = pretrained.mod2 |
| 46 | + self.mod3 = pretrained.mod3 |
| 47 | + self.mod4 = pretrained.mod4 |
| 48 | + self.mod5 = pretrained.mod5 |
| 49 | + self.mod6 = pretrained.mod6 |
| 50 | + self.mod7 = pretrained.mod7 |
| 51 | + self.pool2 = pretrained.pool2 |
| 52 | + self.pool3 = pretrained.pool3 |
| 53 | + del pretrained |
| 54 | + self.head = _DeepLabHead(nclass, height=height//2, width=width//2, **kwargs) |
| 55 | + self.head.initialize(ctx=ctx) |
| 56 | + |
| 57 | + def hybrid_forward(self, F, x): |
| 58 | + outputs = [] |
| 59 | + x = self.mod1(x) |
| 60 | + m2 = self.mod2(self.pool2(x)) |
| 61 | + x = self.mod3(self.pool3(m2)) |
| 62 | + x = self.mod4(x) |
| 63 | + x = self.mod5(x) |
| 64 | + x = self.mod6(x) |
| 65 | + x = self.mod7(x) |
| 66 | + x = self.head(x, m2) |
| 67 | + x = F.contrib.BilinearResize2D(x, **self._up_kwargs) |
| 68 | + outputs.append(x) |
| 69 | + return tuple(outputs) |
| 70 | + |
| 71 | + def demo(self, x): |
| 72 | + return self.predict(x) |
| 73 | + |
| 74 | + def predict(self, x): |
| 75 | + h, w = x.shape[2:] |
| 76 | + self._up_kwargs['height'] = h |
| 77 | + self._up_kwargs['width'] = w |
| 78 | + x = self.mod1(x) |
| 79 | + m2 = self.mod2(self.pool2(x)) |
| 80 | + x = self.mod3(self.pool3(m2)) |
| 81 | + x = self.mod4(x) |
| 82 | + x = self.mod5(x) |
| 83 | + x = self.mod6(x) |
| 84 | + x = self.mod7(x) |
| 85 | + x = self.head.demo(x, m2) |
| 86 | + import mxnet.ndarray as F |
| 87 | + x = F.contrib.BilinearResize2D(x, **self._up_kwargs) |
| 88 | + return x |
| 89 | + |
| 90 | +class _DeepLabHead(HybridBlock): |
| 91 | + def __init__(self, nclass, c1_channels=128, norm_layer=nn.BatchNorm, norm_kwargs=None, |
| 92 | + height=240, width=240, **kwargs): |
| 93 | + super(_DeepLabHead, self).__init__() |
| 94 | + self._up_kwargs = {'height': height, 'width': width} |
| 95 | + with self.name_scope(): |
| 96 | + self.aspp = _ASPP(in_channels=4096, atrous_rates=[12, 24, 36], norm_layer=norm_layer, |
| 97 | + norm_kwargs=norm_kwargs, height=height//4, width=width//4, **kwargs) |
| 98 | + |
| 99 | + self.c1_block = nn.HybridSequential(prefix='bot_fine_') |
| 100 | + self.c1_block.add(nn.Conv2D(in_channels=c1_channels, channels=48, |
| 101 | + kernel_size=1, use_bias=False)) |
| 102 | + |
| 103 | + self.block = nn.HybridSequential(prefix='final_') |
| 104 | + self.block.add(nn.Conv2D(in_channels=304, channels=256, |
| 105 | + kernel_size=3, padding=1, use_bias=False)) |
| 106 | + self.block.add(norm_layer(in_channels=256, |
| 107 | + **({} if norm_kwargs is None else norm_kwargs))) |
| 108 | + self.block.add(nn.Activation('relu')) |
| 109 | + self.block.add(nn.Conv2D(in_channels=256, channels=256, |
| 110 | + kernel_size=3, padding=1, use_bias=False)) |
| 111 | + self.block.add(norm_layer(in_channels=256, |
| 112 | + **({} if norm_kwargs is None else norm_kwargs))) |
| 113 | + self.block.add(nn.Activation('relu')) |
| 114 | + self.block.add(nn.Conv2D(in_channels=256, channels=nclass, |
| 115 | + kernel_size=1, use_bias=False)) |
| 116 | + |
| 117 | + def hybrid_forward(self, F, x, c1): |
| 118 | + c1 = self.c1_block(c1) |
| 119 | + x = self.aspp(x) |
| 120 | + x = F.contrib.BilinearResize2D(x, **self._up_kwargs) |
| 121 | + return self.block(F.concat(c1, x, dim=1)) |
| 122 | + |
| 123 | + def demo(self, x, c1): |
| 124 | + h, w = c1.shape[2:] |
| 125 | + self._up_kwargs['height'] = h |
| 126 | + self._up_kwargs['width'] = w |
| 127 | + c1 = self.c1_block(c1) |
| 128 | + x = self.aspp.demo(x) |
| 129 | + import mxnet.ndarray as F |
| 130 | + x = F.contrib.BilinearResize2D(x, **self._up_kwargs) |
| 131 | + return self.block(F.concat(c1, x, dim=1)) |
| 132 | + |
| 133 | +def _ASPPConv(in_channels, out_channels, atrous_rate, norm_layer, norm_kwargs): |
| 134 | + block = nn.HybridSequential() |
| 135 | + with block.name_scope(): |
| 136 | + block.add(nn.Conv2D(in_channels=in_channels, channels=out_channels, |
| 137 | + kernel_size=3, padding=atrous_rate, |
| 138 | + dilation=atrous_rate, use_bias=False)) |
| 139 | + block.add(norm_layer(in_channels=out_channels, |
| 140 | + **({} if norm_kwargs is None else norm_kwargs))) |
| 141 | + block.add(nn.Activation('relu')) |
| 142 | + return block |
| 143 | + |
| 144 | +class _AsppPooling(nn.HybridBlock): |
| 145 | + def __init__(self, in_channels, out_channels, norm_layer, norm_kwargs, |
| 146 | + height=60, width=60, **kwargs): |
| 147 | + super(_AsppPooling, self).__init__() |
| 148 | + self.gap = nn.HybridSequential() |
| 149 | + self._up_kwargs = {'height': height, 'width': width} |
| 150 | + with self.gap.name_scope(): |
| 151 | + self.gap.add(nn.GlobalAvgPool2D()) |
| 152 | + self.gap.add(nn.Conv2D(in_channels=in_channels, channels=out_channels, |
| 153 | + kernel_size=1, use_bias=False)) |
| 154 | + self.gap.add(norm_layer(in_channels=out_channels, |
| 155 | + **({} if norm_kwargs is None else norm_kwargs))) |
| 156 | + self.gap.add(nn.Activation("relu")) |
| 157 | + |
| 158 | + def hybrid_forward(self, F, x): |
| 159 | + pool = self.gap(x) |
| 160 | + return F.contrib.BilinearResize2D(pool, **self._up_kwargs) |
| 161 | + |
| 162 | + def demo(self, x): |
| 163 | + h, w = x.shape[2:] |
| 164 | + self._up_kwargs['height'] = h |
| 165 | + self._up_kwargs['width'] = w |
| 166 | + pool = self.gap(x) |
| 167 | + import mxnet.ndarray as F |
| 168 | + return F.contrib.BilinearResize2D(pool, **self._up_kwargs) |
| 169 | + |
| 170 | +class _ASPP(nn.HybridBlock): |
| 171 | + def __init__(self, in_channels, atrous_rates, norm_layer, norm_kwargs, |
| 172 | + height=60, width=60): |
| 173 | + super(_ASPP, self).__init__() |
| 174 | + out_channels = 256 |
| 175 | + self.b0 = nn.HybridSequential() |
| 176 | + self.b0.add(nn.Conv2D(in_channels=in_channels, channels=out_channels, |
| 177 | + kernel_size=1, use_bias=False)) |
| 178 | + self.b0.add(norm_layer(in_channels=out_channels, |
| 179 | + **({} if norm_kwargs is None else norm_kwargs))) |
| 180 | + self.b0.add(nn.Activation("relu")) |
| 181 | + |
| 182 | + rate1, rate2, rate3 = tuple(atrous_rates) |
| 183 | + self.b1 = _ASPPConv(in_channels, out_channels, rate1, norm_layer, norm_kwargs) |
| 184 | + self.b2 = _ASPPConv(in_channels, out_channels, rate2, norm_layer, norm_kwargs) |
| 185 | + self.b3 = _ASPPConv(in_channels, out_channels, rate3, norm_layer, norm_kwargs) |
| 186 | + self.b4 = _AsppPooling(in_channels, out_channels, norm_layer=norm_layer, |
| 187 | + norm_kwargs=norm_kwargs, height=height, width=width) |
| 188 | + |
| 189 | + self.project = nn.HybridSequential(prefix='bot_aspp_') |
| 190 | + self.project.add(nn.Conv2D(in_channels=5*out_channels, channels=out_channels, |
| 191 | + kernel_size=1, use_bias=False)) |
| 192 | + |
| 193 | + def hybrid_forward(self, F, x): |
| 194 | + feat1 = self.b0(x) |
| 195 | + feat2 = self.b1(x) |
| 196 | + feat3 = self.b2(x) |
| 197 | + feat4 = self.b3(x) |
| 198 | + x = self.b4(x) |
| 199 | + x = F.concat(x, feat1, feat2, feat3, feat4, dim=1) |
| 200 | + return self.project(x) |
| 201 | + |
| 202 | + def demo(self, x): |
| 203 | + feat1 = self.b0(x) |
| 204 | + feat2 = self.b1(x) |
| 205 | + feat3 = self.b2(x) |
| 206 | + feat4 = self.b3(x) |
| 207 | + x = self.b4.demo(x) |
| 208 | + import mxnet.ndarray as F |
| 209 | + x = F.concat(x, feat1, feat2, feat3, feat4, dim=1) |
| 210 | + return self.project(x) |
| 211 | + |
| 212 | +def get_deeplabv3b_plus(dataset='citys', backbone='wideresnet', pretrained=False, |
| 213 | + root='~/.mxnet/models', ctx=cpu(0), **kwargs): |
| 214 | + r"""DeepLabWV3Plus |
| 215 | + Parameters |
| 216 | + ---------- |
| 217 | + dataset : str, default pascal_voc |
| 218 | + The dataset that model pretrained on. (pascal_voc, ade20k, citys) |
| 219 | + pretrained : bool or str |
| 220 | + Boolean value controls whether to load the default pretrained weights for model. |
| 221 | + String value represents the hashtag for a certain version of pretrained weights. |
| 222 | + ctx : Context, default CPU |
| 223 | + The context in which to load the pretrained weights. |
| 224 | + root : str, default '~/.mxnet/models' |
| 225 | + Location for keeping the model parameters. |
| 226 | +
|
| 227 | + Examples |
| 228 | + -------- |
| 229 | + >>> model = get_deeplabv3b_plus(dataset='citys', backbone='wideresnet', pretrained=False) |
| 230 | + >>> print(model) |
| 231 | + """ |
| 232 | + acronyms = { |
| 233 | + 'pascal_voc': 'voc', |
| 234 | + 'pascal_aug': 'voc', |
| 235 | + 'ade20k': 'ade', |
| 236 | + 'coco': 'coco', |
| 237 | + 'citys': 'citys', |
| 238 | + } |
| 239 | + from ..data import datasets |
| 240 | + # infer number of classes |
| 241 | + model = DeepLabWV3Plus(datasets[dataset].NUM_CLASS, backbone=backbone, ctx=ctx, **kwargs) |
| 242 | + model.classes = datasets[dataset].classes |
| 243 | + if pretrained: |
| 244 | + from .model_store import get_model_file |
| 245 | + model.load_parameters(get_model_file('deeplab_v3b_plus_%s_%s'%(backbone, acronyms[dataset]), |
| 246 | + tag=pretrained, root=root), ctx=ctx) |
| 247 | + return model |
| 248 | + |
| 249 | +def get_deeplab_v3b_plus_wideresnet_citys(**kwargs): |
| 250 | + r"""DeepLabWV3Plus |
| 251 | + Parameters |
| 252 | + ---------- |
| 253 | + pretrained : bool or str |
| 254 | + Boolean value controls whether to load the default pretrained weights for model. |
| 255 | + String value represents the hashtag for a certain version of pretrained weights. |
| 256 | + ctx : Context, default CPU |
| 257 | + The context in which to load the pretrained weights. |
| 258 | + root : str, default '~/.mxnet/models' |
| 259 | + Location for keeping the model parameters. |
| 260 | +
|
| 261 | + Examples |
| 262 | + -------- |
| 263 | + >>> model = get_deeplab_v3b_plus_wideresnet_citys(pretrained=True) |
| 264 | + >>> print(model) |
| 265 | + """ |
| 266 | + return get_deeplabv3b_plus('citys', 'wideresnet', **kwargs) |
0 commit comments