hourglass_pose.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. """
  2. Hourglass network inserted in the pre-activated Resnet
  3. Use lr=0.01 for current version
  4. (c) Yichao Zhou (LCNN)
  5. (c) YANG, Wei
  6. """
  7. import torch
  8. import torch.nn as nn
  9. import torch.nn.functional as F
  10. __all__ = ["HourglassNet", "hg"]
  11. class Bottleneck2D(nn.Module):
  12. expansion = 2 # 扩展因子
  13. def __init__(self, inplanes, planes, stride=1, downsample=None):
  14. super(Bottleneck2D, self).__init__()
  15. self.bn1 = nn.BatchNorm2d(inplanes)
  16. self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1)
  17. self.bn2 = nn.BatchNorm2d(planes)
  18. self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1)
  19. self.bn3 = nn.BatchNorm2d(planes)
  20. self.conv3 = nn.Conv2d(planes, planes * 2, kernel_size=1)
  21. self.relu = nn.ReLU(inplace=True)
  22. self.downsample = downsample
  23. self.stride = stride
  24. def forward(self, x):
  25. residual = x
  26. out = self.bn1(x)
  27. out = self.relu(out)
  28. out = self.conv1(out)
  29. out = self.bn2(out)
  30. out = self.relu(out)
  31. out = self.conv2(out)
  32. out = self.bn3(out)
  33. out = self.relu(out)
  34. out = self.conv3(out)
  35. if self.downsample is not None:
  36. residual = self.downsample(x)
  37. out += residual
  38. return out
  39. class Hourglass(nn.Module):
  40. def __init__(self, block, num_blocks, planes, depth):
  41. super(Hourglass, self).__init__()
  42. self.depth = depth
  43. self.block = block
  44. self.hg = self._make_hour_glass(block, num_blocks, planes, depth)
  45. def _make_residual(self, block, num_blocks, planes):
  46. layers = []
  47. for i in range(0, num_blocks):
  48. layers.append(block(planes * block.expansion, planes))
  49. return nn.Sequential(*layers)
  50. def _make_hour_glass(self, block, num_blocks, planes, depth):
  51. hg = []
  52. for i in range(depth):
  53. res = []
  54. for j in range(3):
  55. res.append(self._make_residual(block, num_blocks, planes))
  56. if i == 0:
  57. res.append(self._make_residual(block, num_blocks, planes))
  58. hg.append(nn.ModuleList(res))
  59. return nn.ModuleList(hg)
  60. def _hour_glass_forward(self, n, x):
  61. up1 = self.hg[n - 1][0](x)
  62. low1 = F.max_pool2d(x, 2, stride=2)
  63. low1 = self.hg[n - 1][1](low1)
  64. if n > 1:
  65. low2 = self._hour_glass_forward(n - 1, low1)
  66. else:
  67. low2 = self.hg[n - 1][3](low1)
  68. low3 = self.hg[n - 1][2](low2)
  69. up2 = F.interpolate(low3, scale_factor=2)
  70. out = up1 + up2
  71. return out
  72. def forward(self, x):
  73. return self._hour_glass_forward(self.depth, x)
  74. class HourglassNet(nn.Module):
  75. """Hourglass model from Newell et al ECCV 2016"""
  76. def __init__(self, block, head, depth, num_stacks, num_blocks, num_classes):
  77. super(HourglassNet, self).__init__()
  78. self.inplanes = 64
  79. self.num_feats = 128
  80. self.num_stacks = num_stacks
  81. self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3)
  82. self.bn1 = nn.BatchNorm2d(self.inplanes)
  83. self.relu = nn.ReLU(inplace=True)
  84. self.layer1 = self._make_residual(block, self.inplanes, 1)
  85. self.layer2 = self._make_residual(block, self.inplanes, 1)
  86. self.layer3 = self._make_residual(block, self.num_feats, 1)
  87. self.maxpool = nn.MaxPool2d(2, stride=2)
  88. # build hourglass modules
  89. ch = self.num_feats * block.expansion
  90. # vpts = []
  91. hg, res, fc, score, fc_, score_ = [], [], [], [], [], []
  92. for i in range(num_stacks):
  93. hg.append(Hourglass(block, num_blocks, self.num_feats, depth))
  94. res.append(self._make_residual(block, self.num_feats, num_blocks))
  95. fc.append(self._make_fc(ch, ch))
  96. score.append(head(ch, num_classes))
  97. # vpts.append(VptsHead(ch))
  98. # vpts.append(nn.Linear(ch, 9))
  99. # score.append(nn.Conv2d(ch, num_classes, kernel_size=1))
  100. # score[i].bias.data[0] += 4.6
  101. # score[i].bias.data[2] += 4.6
  102. if i < num_stacks - 1:
  103. fc_.append(nn.Conv2d(ch, ch, kernel_size=1))
  104. score_.append(nn.Conv2d(num_classes, ch, kernel_size=1))
  105. self.hg = nn.ModuleList(hg)
  106. self.res = nn.ModuleList(res)
  107. self.fc = nn.ModuleList(fc)
  108. self.score = nn.ModuleList(score)
  109. # self.vpts = nn.ModuleList(vpts)
  110. self.fc_ = nn.ModuleList(fc_)
  111. self.score_ = nn.ModuleList(score_)
  112. def _make_residual(self, block, planes, blocks, stride=1):
  113. downsample = None
  114. if stride != 1 or self.inplanes != planes * block.expansion:
  115. downsample = nn.Sequential(
  116. nn.Conv2d(
  117. self.inplanes,
  118. planes * block.expansion,
  119. kernel_size=1,
  120. stride=stride,
  121. )
  122. )
  123. layers = []
  124. layers.append(block(self.inplanes, planes, stride, downsample))
  125. self.inplanes = planes * block.expansion
  126. for i in range(1, blocks):
  127. layers.append(block(self.inplanes, planes))
  128. return nn.Sequential(*layers)
  129. def _make_fc(self, inplanes, outplanes):
  130. bn = nn.BatchNorm2d(inplanes)
  131. conv = nn.Conv2d(inplanes, outplanes, kernel_size=1)
  132. return nn.Sequential(conv, bn, self.relu)
  133. def forward(self, x):
  134. out = []
  135. # out_vps = []
  136. x = self.conv1(x)
  137. x = self.bn1(x)
  138. x = self.relu(x)
  139. x = self.layer1(x)
  140. x = self.maxpool(x)
  141. x = self.layer2(x)
  142. x = self.layer3(x)
  143. for i in range(self.num_stacks):
  144. y = self.hg[i](x)
  145. y = self.res[i](y)
  146. y = self.fc[i](y)
  147. score = self.score[i](y)
  148. # pre_vpts = F.adaptive_avg_pool2d(x, (1, 1))
  149. # pre_vpts = pre_vpts.reshape(-1, 256)
  150. # vpts = self.vpts[i](x)
  151. out.append(score)
  152. # out_vps.append(vpts)
  153. if i < self.num_stacks - 1:
  154. fc_ = self.fc_[i](y)
  155. score_ = self.score_[i](score)
  156. x = x + fc_ + score_
  157. return out[::-1], y # , out_vps[::-1]
  158. def hg(**kwargs):
  159. model = HourglassNet(
  160. Bottleneck2D,
  161. head=kwargs.get("head", lambda c_in, c_out: nn.Conv2D(c_in, c_out, 1)),
  162. depth=kwargs["depth"],
  163. num_stacks=kwargs["num_stacks"],
  164. num_blocks=kwargs["num_blocks"],
  165. num_classes=kwargs["num_classes"],
  166. )
  167. return model