You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

model_define.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import os
  2. import torch
  3. from torch import nn
  4. import torch.nn.functional as F
  5. from collections import OrderedDict
  6. class ASPP(nn.Module):
  7. # have bias and relu, no bn
  8. def __init__(self, in_channel=512, depth=256):
  9. super().__init__()
  10. # global average pooling : init nn.AdaptiveAvgPool2d ;also forward torch.mean(,,keep_dim=True)
  11. self.mean = nn.AdaptiveAvgPool2d((1, 1))
  12. self.conv = nn.Sequential(nn.Conv2d(in_channel, depth, 1, 1),
  13. nn.ReLU(inplace=True))
  14. self.atrous_block1 = nn.Sequential(nn.Conv2d(in_channel, depth, 1, 1),
  15. nn.ReLU(inplace=True))
  16. self.atrous_block6 = nn.Sequential(
  17. nn.Conv2d(in_channel, depth, 3, 1, padding=3, dilation=3),
  18. nn.ReLU(inplace=True))
  19. self.atrous_block12 = nn.Sequential(
  20. nn.Conv2d(in_channel, depth, 3, 1, padding=6, dilation=6),
  21. nn.ReLU(inplace=True))
  22. self.atrous_block18 = nn.Sequential(
  23. nn.Conv2d(in_channel, depth, 3, 1, padding=9, dilation=9),
  24. nn.ReLU(inplace=True))
  25. self.conv_1x1_output = nn.Sequential(nn.Conv2d(depth * 5, depth, 1, 1),
  26. nn.ReLU(inplace=True))
  27. def forward(self, x):
  28. size = x.shape[2:]
  29. image_features = self.mean(x)
  30. image_features = self.conv(image_features)
  31. image_features = F.interpolate(image_features,
  32. size=size,
  33. mode='bilinear',
  34. align_corners=True)
  35. atrous_block1 = self.atrous_block1(x)
  36. atrous_block6 = self.atrous_block6(x)
  37. atrous_block12 = self.atrous_block12(x)
  38. atrous_block18 = self.atrous_block18(x)
  39. net = self.conv_1x1_output(
  40. torch.cat([
  41. image_features, atrous_block1, atrous_block6, atrous_block12,
  42. atrous_block18
  43. ],
  44. dim=1))
  45. return net
  46. class ResNet(nn.Module):
  47. def __init__(self, block, layers, num_classes=18, zero_init_residual=False,
  48. groups=1, width_per_group=64, replace_stride_with_dilation=None,
  49. norm_layer=None):
  50. super(ResNet, self).__init__()
  51. if norm_layer is None:
  52. norm_layer = nn.BatchNorm2d
  53. self._norm_layer = norm_layer
  54. self.inplanes = 64
  55. self.dilation = 1
  56. if replace_stride_with_dilation is None:
  57. # each element in the tuple indicates if we should replace
  58. # the 2x2 stride with a dilated convolution instead
  59. replace_stride_with_dilation = [False, False, False]
  60. if len(replace_stride_with_dilation) != 3:
  61. raise ValueError("replace_stride_with_dilation should be None "
  62. "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
  63. self.groups = groups
  64. self.base_width = width_per_group
  65. self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
  66. bias=False)
  67. self.bn1 = norm_layer(self.inplanes)
  68. self.relu = nn.ReLU(inplace=True)
  69. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  70. self.layer1 = self._make_layer(block, 64, layers[0])
  71. self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
  72. dilate=replace_stride_with_dilation[0])
  73. self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
  74. dilate=replace_stride_with_dilation[1])
  75. self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
  76. dilate=replace_stride_with_dilation[2])
  77. self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
  78. self.fc = nn.Linear(512 * block.expansion, num_classes)
  79. for m in self.modules():
  80. if isinstance(m, nn.Conv2d):
  81. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  82. elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
  83. nn.init.constant_(m.weight, 1)
  84. nn.init.constant_(m.bias, 0)
  85. # Zero-initialize the last BN in each residual branch,
  86. # so that the residual branch starts with zeros, and each residual block behaves like an identity.
  87. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
  88. #加入归一化层,对是否进行归一化进行判断
  89. if zero_init_residual:
  90. for m in self.modules():
  91. if isinstance(m, Bottleneck):
  92. nn.init.constant_(m.bn3.weight, 0)
  93. elif isinstance(m, BasicBlock):
  94. nn.init.constant_(m.bn2.weight, 0)
  95. def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
  96. norm_layer = self._norm_layer
  97. downsample = None
  98. previous_dilation = self.dilation
  99. if dilate:
  100. self.dilation *= stride
  101. stride = 1
  102. if stride != 1 or self.inplanes != planes * block.expansion:
  103. downsample = nn.Sequential(
  104. conv1x1(self.inplanes, planes * block.expansion, stride),
  105. norm_layer(planes * block.expansion),
  106. )
  107. layers = []
  108. layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
  109. self.base_width, previous_dilation, norm_layer))
  110. self.inplanes = planes * block.expansion
  111. for _ in range(1, blocks):
  112. layers.append(block(self.inplanes, planes, groups=self.groups,
  113. base_width=self.base_width, dilation=self.dilation,
  114. norm_layer=norm_layer))
  115. return nn.Sequential(*layers)
  116. def forward(self, x):
  117. x = self.conv1(x)
  118. x = self.bn1(x)
  119. x = self.relu(x)
  120. x = self.maxpool(x)
  121. x = self.layer1(x)
  122. x = self.layer2(x)
  123. x = self.layer3(x)
  124. x = self.layer4(x)
  125. x = self.avgpool(x)
  126. x = torch.flatten(x, 1)
  127. x = self.fc(x)
  128. return x
  129. def _resnet(arch, block, layers, pretrained, progress, **kwargs):
  130. model = ResNet(block, layers, **kwargs)
  131. return model
  132. def resnet50(pretrained=False, progress=True, **kwargs):
  133. return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
  134. **kwargs)
  135. def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
  136. """3x3 convolution with padding"""
  137. return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
  138. padding=dilation, groups=groups, bias=False, dilation=dilation)
  139. def conv1x1(in_planes, out_planes, stride=1):
  140. """1x1 convolution"""
  141. return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
  142. class BasicBlock(nn.Module):
  143. expansion = 1
  144. def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
  145. base_width=64, dilation=1, norm_layer=None):
  146. super(BasicBlock, self).__init__()
  147. if norm_layer is None:
  148. norm_layer = nn.BatchNorm2d
  149. if groups != 1 or base_width != 64:
  150. raise ValueError('BasicBlock only supports groups=1 and base_width=64')
  151. if dilation > 1:
  152. raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
  153. # Both self.conv1 and self.downsample layers downsample the input when stride != 1
  154. self.conv1 = conv3x3(inplanes, planes, stride)
  155. self.bn1 = norm_layer(planes)
  156. self.relu = nn.ReLU(inplace=True)
  157. self.conv2 = conv3x3(planes, planes)
  158. self.bn2 = norm_layer(planes)
  159. self.downsample = downsample
  160. self.stride = stride
  161. def forward(self, x):
  162. identity = x
  163. out = self.conv1(x)
  164. out = self.bn1(out)
  165. out = self.relu(out)
  166. out = self.conv2(out)
  167. out = self.bn2(out)
  168. if self.downsample is not None:
  169. identity = self.downsample(x)
  170. out += identity
  171. out = self.relu(out)
  172. return out
  173. class Bottleneck(nn.Module):
  174. expansion = 4
  175. def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
  176. base_width=64, dilation=1, norm_layer=None):
  177. super(Bottleneck, self).__init__()
  178. if norm_layer is None:
  179. norm_layer = nn.BatchNorm2d
  180. width = int(planes * (base_width / 64.)) * groups
  181. # Both self.conv2 and self.downsample layers downsample the input when stride != 1
  182. self.conv1 = conv1x1(inplanes, width)
  183. self.bn1 = norm_layer(width)
  184. self.conv2 = conv3x3(width, width, stride, groups, dilation)
  185. self.bn2 = norm_layer(width)
  186. self.conv3 = conv1x1(width, planes * self.expansion)
  187. self.bn3 = norm_layer(planes * self.expansion)
  188. self.relu = nn.ReLU(inplace=True)
  189. self.downsample = downsample
  190. self.stride = stride
  191. def forward(self, x):
  192. identity = x
  193. out = self.conv1(x)
  194. out = self.bn1(out)
  195. out = self.relu(out)
  196. out = self.conv2(out)
  197. out = self.bn2(out)
  198. out = self.relu(out)
  199. out = self.conv3(out)
  200. out = self.bn3(out)
  201. if self.downsample is not None:
  202. identity = self.downsample(x)
  203. out += identity
  204. out = self.relu(out)
  205. return out
  206. class Deeplab_v3(nn.Module):
  207. # in_channel = 3 fine-tune
  208. def __init__(self, class_number=18):
  209. super().__init__()
  210. encoder = resnet50()
  211. self.start = nn.Sequential(encoder.conv1, encoder.bn1, encoder.relu)
  212. self.maxpool = encoder.maxpool
  213. self.low_feature1 = nn.Sequential(nn.Conv2d(
  214. 64, 32, 1, 1), nn.BatchNorm2d(32), nn.ReLU(inplace=True))
  215. self.low_feature3 = nn.Sequential(nn.Conv2d(
  216. 256, 64, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True))
  217. self.low_feature4 = nn.Sequential(nn.Conv2d(
  218. 512, 128, 1, 1), nn.BatchNorm2d(128), nn.ReLU(inplace=True))
  219. self.layer1 = encoder.layer1 #256
  220. self.layer2 = encoder.layer2 #512
  221. self.layer3 = encoder.layer3 #1024
  222. self.layer4 = encoder.layer4 #2048
  223. self.aspp = ASPP(in_channel=2048, depth=256)
  224. self.conv_cat4 = nn.Sequential(nn.Conv2d(256 + 128, 256, 3, 1, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True))
  225. self.conv_cat3 = nn.Sequential(nn.Conv2d(256 + 64, 256, 3, 1, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True),
  226. nn.Conv2d(256, 64, 3, 1, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True))
  227. self.conv_cat1 = nn.Sequential(nn.Conv2d(64 + 32, 64, 3, 1, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True),
  228. nn.Conv2d(64, 18, 3, 1, padding=1))
  229. def forward(self, x):
  230. size0 = x.shape[2:] # need upsample input size
  231. x1 = self.start(x) # 64, 128*128
  232. x2 = self.maxpool(x1) # 64, 64*64
  233. x3 = self.layer1(x2) # 256, 64*64
  234. x4 = self.layer2(x3) # 512, 32*32
  235. x5 = self.layer3(x4) # 1024,16*16
  236. x = self.layer4(x5) # 2048,8*8
  237. x = self.aspp(x) # 256, 8*8
  238. low_feature1 = self.low_feature1(x1) # 64, 128*128
  239. # low_feature2 = self.low_feature2(x2) # 64, 64*64
  240. low_feature3 = self.low_feature3(x3) # 256, 64*64
  241. low_feature4 = self.low_feature4(x4) # 512, 32*32 -> 128, 32*32
  242. # low_feature5 = self.low_feature5(x5) # 1024,16*16
  243. size1 = low_feature1.shape[2:]
  244. # size2 = low_feature2.shape[2:]
  245. size3 = low_feature3.shape[2:]
  246. size4 = low_feature4.shape[2:]
  247. # size5 = low_feature5.shape[2:]
  248. decoder_feature4 = F.interpolate(x, size=size4, mode='bilinear', align_corners=True)
  249. x = self.conv_cat4(torch.cat([low_feature4, decoder_feature4], dim=1))
  250. decoder_feature3 = F.interpolate(x, size=size3, mode='bilinear', align_corners=True)
  251. x = self.conv_cat3(torch.cat([low_feature3, decoder_feature3], dim=1))
  252. decoder_feature1 = F.interpolate(x, size=size1, mode='bilinear', align_corners=True)
  253. x = self.conv_cat1(torch.cat([low_feature1, decoder_feature1], dim=1))
  254. score = F.interpolate(x,
  255. size=size0,
  256. mode='bilinear',
  257. align_corners=True)
  258. return score
  259. def init_model():
  260. model_path = os.path.join(os.path.dirname(__file__), 'model.pkl')
  261. model = Deeplab_v3()
  262. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  263. model.to(device)
  264. model_state = torch.load(model_path, map_location=device)
  265. new_state_dict = OrderedDict()
  266. for k, v in model_state["model_state_dict"].items():
  267. if k[:7] == "module.":
  268. new_state_dict[k[7:]] = v
  269. else:
  270. new_state_dict[k] = v
  271. model.load_state_dict(new_state_dict)
  272. model.eval()
  273. return model