torch_det_model.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import torch
  2. import torch.nn as nn
  3. import numpy as np
  4. import math
  5. import os
  6. from torch.nn import functional as F
  7. import torch.nn.init as init
  8. import logging
  9. class HSwish(nn.Module):
  10. def forward(self, x):
  11. out = x * F.relu6(x + 3, inplace=True) / 6
  12. return out
  13. class ConvBNACT(nn.Module):
  14. def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, act=None):
  15. super().__init__()
  16. self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
  17. stride=stride, padding=padding, groups=groups,
  18. bias=False)
  19. self.bn = nn.BatchNorm2d(out_channels)
  20. if act == 'relu':
  21. self.act = nn.ReLU(inplace=True)
  22. elif act == 'hard_swish':
  23. self.act = HSwish()
  24. elif act is None:
  25. self.act = None
  26. def forward(self, x):
  27. x = self.conv(x)
  28. x = self.bn(x)
  29. if self.act is not None:
  30. x = self.act(x)
  31. return x
  32. class ConvBNACTWithPool(nn.Module):
  33. def __init__(self, in_channels, out_channels, kernel_size, groups=1, act=None):
  34. super().__init__()
  35. # self.pool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0, ceil_mode=True)
  36. self.pool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
  37. self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1,
  38. padding=(kernel_size - 1) // 2,
  39. groups=groups,
  40. bias=False)
  41. self.bn = nn.BatchNorm2d(out_channels)
  42. if act is None:
  43. self.act = None
  44. else:
  45. self.act = nn.ReLU(inplace=True)
  46. def forward(self, x):
  47. x = self.pool(x)
  48. x = self.conv(x)
  49. x = self.bn(x)
  50. if self.act is not None:
  51. x = self.act(x)
  52. return x
  53. class ShortCut(nn.Module):
  54. def __init__(self, in_channels, out_channels, stride, name, if_first=False):
  55. super().__init__()
  56. assert name is not None, 'shortcut must have name'
  57. self.name = name
  58. if in_channels != out_channels or stride != 1:
  59. if if_first:
  60. self.conv = ConvBNACT(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride,
  61. padding=0, groups=1, act=None)
  62. else:
  63. self.conv = ConvBNACTWithPool(in_channels=in_channels, out_channels=out_channels, kernel_size=1,
  64. groups=1, act=None)
  65. elif if_first:
  66. self.conv = ConvBNACT(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride,
  67. padding=0, groups=1, act=None)
  68. else:
  69. self.conv = None
  70. def forward(self, x):
  71. if self.conv is not None:
  72. x = self.conv(x)
  73. return x
  74. class BottleneckBlock(nn.Module):
  75. def __init__(self, in_channels, out_channels, stride, if_first, name):
  76. super().__init__()
  77. assert name is not None, 'bottleneck must have name'
  78. self.name = name
  79. self.conv0 = ConvBNACT(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0,
  80. groups=1, act='relu')
  81. self.conv1 = ConvBNACT(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=stride,
  82. padding=1, groups=1, act='relu')
  83. self.conv2 = ConvBNACT(in_channels=out_channels, out_channels=out_channels * 4, kernel_size=1, stride=1,
  84. padding=0, groups=1, act=None)
  85. self.shortcut = ShortCut(in_channels=in_channels, out_channels=out_channels * 4, stride=stride,
  86. if_first=if_first, name=f'{name}_branch1')
  87. self.relu = nn.ReLU(inplace=True)
  88. self.output_channels = out_channels * 4
  89. def forward(self, x):
  90. y = self.conv0(x)
  91. y = self.conv1(y)
  92. y = self.conv2(y)
  93. y = y + self.shortcut(x)
  94. return self.relu(y)
  95. class BasicBlock(nn.Module):
  96. def __init__(self, in_channels, out_channels, stride, if_first, name):
  97. super().__init__()
  98. assert name is not None, 'block must have name'
  99. self.name = name
  100. self.conv0 = ConvBNACT(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride,
  101. padding=1, groups=1, act='relu')
  102. self.conv1 = ConvBNACT(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1,
  103. groups=1, act=None)
  104. self.shortcut = ShortCut(in_channels=in_channels, out_channels=out_channels, stride=stride,
  105. name=f'{name}_branch1', if_first=if_first, )
  106. self.relu = nn.ReLU(inplace=True)
  107. self.output_channels = out_channels
  108. def forward(self, x):
  109. y = self.conv0(x)
  110. y = self.conv1(y)
  111. y = y + self.shortcut(x)
  112. return self.relu(y)
  113. class ResNet(nn.Module):
  114. def __init__(self, in_channels, layers, out_indices=[0, 1, 2, 3], pretrained=True, **kwargs):
  115. """
  116. the Resnet backbone network for detection module.
  117. Args:
  118. params(dict): the super parameters for network build
  119. """
  120. super().__init__()
  121. supported_layers = {
  122. 18: {'depth': [2, 2, 2, 2], 'block_class': BasicBlock},
  123. 34: {'depth': [3, 4, 6, 3], 'block_class': BasicBlock},
  124. 50: {'depth': [3, 4, 6, 3], 'block_class': BottleneckBlock},
  125. 101: {'depth': [3, 4, 23, 3], 'block_class': BottleneckBlock},
  126. 152: {'depth': [3, 8, 36, 3], 'block_class': BottleneckBlock},
  127. 200: {'depth': [3, 12, 48, 3], 'block_class': BottleneckBlock}
  128. }
  129. assert layers in supported_layers, \
  130. "supported layers are {} but input layer is {}".format(supported_layers, layers)
  131. depth = supported_layers[layers]['depth']
  132. block_class = supported_layers[layers]['block_class']
  133. self.use_supervised = kwargs.get('use_supervised', False)
  134. self.out_indices = out_indices
  135. num_filters = [64, 128, 256, 512]
  136. self.conv1 = nn.Sequential(
  137. ConvBNACT(in_channels=in_channels, out_channels=32, kernel_size=3, stride=2, padding=1, act='relu'),
  138. ConvBNACT(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1, act='relu'),
  139. ConvBNACT(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1, act='relu')
  140. )
  141. self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  142. self.stages = nn.ModuleList()
  143. self.out_channels = []
  144. tmp_channels = []
  145. in_ch = 64
  146. for block_index in range(len(depth)):
  147. block_list = []
  148. for i in range(depth[block_index]):
  149. if layers >= 50:
  150. if layers in [101, 152, 200] and block_index == 2:
  151. if i == 0:
  152. conv_name = "res" + str(block_index + 2) + "a"
  153. else:
  154. conv_name = "res" + str(block_index + 2) + "b" + str(i)
  155. else:
  156. conv_name = "res" + str(block_index + 2) + chr(97 + i)
  157. else:
  158. conv_name = f'res{str(block_index + 2)}{chr(97 + i)}'
  159. block_list.append(block_class(in_channels=in_ch, out_channels=num_filters[block_index],
  160. stride=2 if i == 0 and block_index != 0 else 1,
  161. if_first=block_index == i == 0, name=conv_name))
  162. in_ch = block_list[-1].output_channels
  163. tmp_channels.append(in_ch)
  164. self.stages.append(nn.Sequential(*block_list))
  165. for idx, ch in enumerate(tmp_channels):
  166. if idx in self.out_indices:
  167. self.out_channels.append(ch)
  168. if pretrained:
  169. ckpt_path = f'./weights/resnet{layers}_vd.pth'
  170. logger = logging.getLogger('torchocr')
  171. if os.path.exists(ckpt_path):
  172. logger.info('load imagenet weights')
  173. self.load_state_dict(torch.load(ckpt_path))
  174. else:
  175. logger.info(f'{ckpt_path} not exists')
  176. if self.use_supervised:
  177. ckpt_path = f'./weights/res_supervised_140w_387e.pth'
  178. logger = logging.getLogger('torchocr')
  179. if os.path.exists(ckpt_path):
  180. logger.info('load supervised weights')
  181. self.load_state_dict(torch.load(ckpt_path))
  182. else:
  183. logger.info(f'{ckpt_path} not exists')
  184. def forward(self, x):
  185. x = self.conv1(x)
  186. x = self.pool1(x)
  187. out = []
  188. for idx, stage in enumerate(self.stages):
  189. x = stage(x)
  190. if idx in self.out_indices:
  191. out.append(x)
  192. return out
  193. def weights_init(m):
  194. if isinstance(m, nn.Conv2d):
  195. init.kaiming_normal_(m.weight.data)
  196. if m.bias is not None:
  197. init.normal_(m.bias.data)
  198. elif isinstance(m, nn.ConvTranspose2d):
  199. init.kaiming_normal_(m.weight.data)
  200. if m.bias is not None:
  201. init.normal_(m.bias.data)
  202. elif isinstance(m, nn.BatchNorm2d):
  203. init.normal_(m.weight.data, mean=1, std=0.02)
  204. init.constant_(m.bias.data, 0)
  205. class DB_fpn(nn.Module):
  206. def __init__(self, in_channels, out_channels=256, **kwargs):
  207. """
  208. :param in_channels: 基础网络输出的维度
  209. :param kwargs:
  210. """
  211. super().__init__()
  212. inplace = True
  213. self.out_channels = out_channels
  214. # reduce layers
  215. self.in2_conv = nn.Conv2d(in_channels[0], self.out_channels, kernel_size=1, bias=False)
  216. self.in3_conv = nn.Conv2d(in_channels[1], self.out_channels, kernel_size=1, bias=False)
  217. self.in4_conv = nn.Conv2d(in_channels[2], self.out_channels, kernel_size=1, bias=False)
  218. self.in5_conv = nn.Conv2d(in_channels[3], self.out_channels, kernel_size=1, bias=False)
  219. # Smooth layers
  220. self.p5_conv = nn.Conv2d(self.out_channels, self.out_channels // 4, kernel_size=3, padding=1, bias=False)
  221. self.p4_conv = nn.Conv2d(self.out_channels, self.out_channels // 4, kernel_size=3, padding=1, bias=False)
  222. self.p3_conv = nn.Conv2d(self.out_channels, self.out_channels // 4, kernel_size=3, padding=1, bias=False)
  223. self.p2_conv = nn.Conv2d(self.out_channels, self.out_channels // 4, kernel_size=3, padding=1, bias=False)
  224. self.in2_conv.apply(weights_init)
  225. self.in3_conv.apply(weights_init)
  226. self.in4_conv.apply(weights_init)
  227. self.in5_conv.apply(weights_init)
  228. self.p5_conv.apply(weights_init)
  229. self.p4_conv.apply(weights_init)
  230. self.p3_conv.apply(weights_init)
  231. self.p2_conv.apply(weights_init)
  232. def _interpolate_add(self, x, y):
  233. return F.interpolate(x, scale_factor=2) + y
  234. def _interpolate_cat(self, p2, p3, p4, p5):
  235. p3 = F.interpolate(p3, scale_factor=2)
  236. p4 = F.interpolate(p4, scale_factor=4)
  237. p5 = F.interpolate(p5, scale_factor=8)
  238. return torch.cat([p5, p4, p3, p2], dim=1)
  239. def forward(self, x):
  240. c2, c3, c4, c5 = x
  241. in5 = self.in5_conv(c5)
  242. in4 = self.in4_conv(c4)
  243. in3 = self.in3_conv(c3)
  244. in2 = self.in2_conv(c2)
  245. out4 = self._interpolate_add(in5, in4)
  246. out3 = self._interpolate_add(out4, in3)
  247. out2 = self._interpolate_add(out3, in2)
  248. p5 = self.p5_conv(in5)
  249. p4 = self.p4_conv(out4)
  250. p3 = self.p3_conv(out3)
  251. p2 = self.p2_conv(out2)
  252. x = self._interpolate_cat(p2, p3, p4, p5)
  253. return x
  254. class Head(nn.Module):
  255. def __init__(self, in_channels):
  256. super().__init__()
  257. self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=in_channels // 4, kernel_size=3, padding=1,
  258. bias=False)
  259. # self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=in_channels // 4, kernel_size=5, padding=2,
  260. # bias=False)
  261. self.conv_bn1 = nn.BatchNorm2d(in_channels // 4)
  262. self.relu = nn.ReLU(inplace=True)
  263. self.conv2 = nn.ConvTranspose2d(in_channels=in_channels // 4, out_channels=in_channels // 4, kernel_size=2,
  264. stride=2)
  265. self.conv_bn2 = nn.BatchNorm2d(in_channels // 4)
  266. self.conv3 = nn.ConvTranspose2d(in_channels=in_channels // 4, out_channels=1, kernel_size=2, stride=2)
  267. def forward(self, x):
  268. x = self.conv1(x)
  269. x = self.conv_bn1(x)
  270. x = self.relu(x)
  271. x = self.conv2(x)
  272. x = self.conv_bn2(x)
  273. x = self.relu(x)
  274. x = self.conv3(x)
  275. x = torch.sigmoid(x)
  276. return x
  277. class DBHead(nn.Module):
  278. """
  279. Differentiable Binarization (DB) for text detection:
  280. see https://arxiv.org/abs/1911.08947
  281. args:
  282. params(dict): super parameters for build DB network
  283. """
  284. def __init__(self, in_channels, k=50):
  285. super().__init__()
  286. self.k = k
  287. self.binarize = Head(in_channels)
  288. self.thresh = Head(in_channels)
  289. self.binarize.apply(weights_init)
  290. self.thresh.apply(weights_init)
  291. def step_function(self, x, y):
  292. return torch.reciprocal(1 + torch.exp(-self.k * (x - y)))
  293. def forward(self, x):
  294. shrink_maps = self.binarize(x)
  295. if not self.training:
  296. return shrink_maps
  297. threshold_maps = self.thresh(x)
  298. binary_maps = self.step_function(shrink_maps, threshold_maps)
  299. y = torch.cat((shrink_maps, threshold_maps, binary_maps), dim=1)
  300. return y
  301. class DB_ResNet_18(nn.Module):
  302. def __init__(self, ):
  303. super().__init__()
  304. self.backbone = ResNet(in_channels=3,layers=18,pretrained=False)
  305. self.neck = DB_fpn(in_channels=self.backbone.out_channels,out_channels=256)
  306. self.head = DBHead(self.neck.out_channels)
  307. def forward(self, x):
  308. x = self.backbone(x)
  309. x = self.neck(x)
  310. x = self.head(x)
  311. return x