centertrack_head.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. import paddle
  16. import paddle.nn as nn
  17. import paddle.nn.functional as F
  18. from ppdet.core.workspace import register
  19. from .centernet_head import ConvLayer
  20. from ..keypoint_utils import get_affine_transform
  21. __all__ = ['CenterTrackHead']
  22. @register
  23. class CenterTrackHead(nn.Layer):
  24. """
  25. Args:
  26. in_channels (int): the channel number of input to CenterNetHead.
  27. num_classes (int): the number of classes, 1 (MOT17 dataset) by default.
  28. head_planes (int): the channel number in all head, 256 by default.
  29. task (str): the type of task for regression, 'tracking' by default.
  30. loss_weight (dict): the weight of each loss.
  31. add_ltrb_amodal (bool): whether to add ltrb_amodal branch, False by default.
  32. """
  33. __shared__ = ['num_classes']
  34. def __init__(self,
  35. in_channels,
  36. num_classes=1,
  37. head_planes=256,
  38. task='tracking',
  39. loss_weight={
  40. 'tracking': 1.0,
  41. 'ltrb_amodal': 0.1,
  42. },
  43. add_ltrb_amodal=True):
  44. super(CenterTrackHead, self).__init__()
  45. self.task = task
  46. self.loss_weight = loss_weight
  47. self.add_ltrb_amodal = add_ltrb_amodal
  48. # tracking head
  49. self.tracking = nn.Sequential(
  50. ConvLayer(
  51. in_channels, head_planes, kernel_size=3, padding=1, bias=True),
  52. nn.ReLU(),
  53. ConvLayer(
  54. head_planes, 2, kernel_size=1, stride=1, padding=0, bias=True))
  55. # ltrb_amodal head
  56. if self.add_ltrb_amodal and 'ltrb_amodal' in self.loss_weight:
  57. self.ltrb_amodal = nn.Sequential(
  58. ConvLayer(
  59. in_channels,
  60. head_planes,
  61. kernel_size=3,
  62. padding=1,
  63. bias=True),
  64. nn.ReLU(),
  65. ConvLayer(
  66. head_planes,
  67. 4,
  68. kernel_size=1,
  69. stride=1,
  70. padding=0,
  71. bias=True))
  72. # TODO: add more tasks
  73. @classmethod
  74. def from_config(cls, cfg, input_shape):
  75. if isinstance(input_shape, (list, tuple)):
  76. input_shape = input_shape[0]
  77. return {'in_channels': input_shape.channels}
  78. def forward(self,
  79. feat,
  80. inputs,
  81. bboxes=None,
  82. bbox_inds=None,
  83. topk_clses=None,
  84. topk_ys=None,
  85. topk_xs=None):
  86. tracking = self.tracking(feat)
  87. head_outs = {'tracking': tracking}
  88. if self.add_ltrb_amodal and 'ltrb_amodal' in self.loss_weight:
  89. ltrb_amodal = self.ltrb_amodal(feat)
  90. head_outs.update({'ltrb_amodal': ltrb_amodal})
  91. if self.training:
  92. losses = self.get_loss(inputs, self.loss_weight, head_outs)
  93. return losses
  94. else:
  95. ret = self.generic_decode(head_outs, bboxes, bbox_inds, topk_ys,
  96. topk_xs)
  97. return ret
  98. def get_loss(self, inputs, weights, head_outs):
  99. index = inputs['index'].unsqueeze(2)
  100. mask = inputs['index_mask'].unsqueeze(2)
  101. batch_inds = list()
  102. for i in range(head_outs['tracking'].shape[0]):
  103. batch_ind = paddle.full(
  104. shape=[1, index.shape[1], 1], fill_value=i, dtype='int64')
  105. batch_inds.append(batch_ind)
  106. batch_inds = paddle.concat(batch_inds, axis=0)
  107. index = paddle.concat(x=[batch_inds, index], axis=2)
  108. # 1.tracking head loss: L1 loss
  109. tracking = head_outs['tracking'].transpose([0, 2, 3, 1])
  110. tracking_target = inputs['tracking']
  111. bs, _, _, c = tracking.shape
  112. tracking = tracking.reshape([bs, -1, c])
  113. pos_tracking = paddle.gather_nd(tracking, index=index)
  114. tracking_mask = paddle.cast(
  115. paddle.expand_as(mask, pos_tracking), dtype=pos_tracking.dtype)
  116. pos_num = tracking_mask.sum()
  117. tracking_mask.stop_gradient = True
  118. tracking_target.stop_gradient = True
  119. tracking_loss = F.l1_loss(
  120. pos_tracking * tracking_mask,
  121. tracking_target * tracking_mask,
  122. reduction='sum')
  123. tracking_loss = tracking_loss / (pos_num + 1e-4)
  124. # 2.ltrb_amodal head loss(optinal): L1 loss
  125. if self.add_ltrb_amodal and 'ltrb_amodal' in self.loss_weight:
  126. ltrb_amodal = head_outs['ltrb_amodal'].transpose([0, 2, 3, 1])
  127. ltrb_amodal_target = inputs['ltrb_amodal']
  128. bs, _, _, c = ltrb_amodal.shape
  129. ltrb_amodal = ltrb_amodal.reshape([bs, -1, c])
  130. pos_ltrb_amodal = paddle.gather_nd(ltrb_amodal, index=index)
  131. ltrb_amodal_mask = paddle.cast(
  132. paddle.expand_as(mask, pos_ltrb_amodal),
  133. dtype=pos_ltrb_amodal.dtype)
  134. pos_num = ltrb_amodal_mask.sum()
  135. ltrb_amodal_mask.stop_gradient = True
  136. ltrb_amodal_target.stop_gradient = True
  137. ltrb_amodal_loss = F.l1_loss(
  138. pos_ltrb_amodal * ltrb_amodal_mask,
  139. ltrb_amodal_target * ltrb_amodal_mask,
  140. reduction='sum')
  141. ltrb_amodal_loss = ltrb_amodal_loss / (pos_num + 1e-4)
  142. losses = {'tracking_loss': tracking_loss, }
  143. plugin_loss = weights['tracking'] * tracking_loss
  144. if self.add_ltrb_amodal and 'ltrb_amodal' in self.loss_weight:
  145. losses.update({'ltrb_amodal_loss': ltrb_amodal_loss})
  146. plugin_loss += weights['ltrb_amodal'] * ltrb_amodal_loss
  147. losses.update({'plugin_loss': plugin_loss})
  148. return losses
  149. def generic_decode(self, head_outs, bboxes, bbox_inds, topk_ys, topk_xs):
  150. topk_ys = paddle.floor(topk_ys) # note: More accurate
  151. topk_xs = paddle.floor(topk_xs)
  152. cts = paddle.concat([topk_xs, topk_ys], 1)
  153. ret = {'bboxes': bboxes, 'cts': cts}
  154. regression_heads = ['tracking'] # todo: add more tasks
  155. for head in regression_heads:
  156. if head in head_outs:
  157. ret[head] = _tranpose_and_gather_feat(head_outs[head],
  158. bbox_inds)
  159. if 'ltrb_amodal' in head_outs:
  160. ltrb_amodal = head_outs['ltrb_amodal']
  161. ltrb_amodal = _tranpose_and_gather_feat(ltrb_amodal, bbox_inds)
  162. bboxes_amodal = paddle.concat(
  163. [
  164. topk_xs * 1.0 + ltrb_amodal[..., 0:1],
  165. topk_ys * 1.0 + ltrb_amodal[..., 1:2],
  166. topk_xs * 1.0 + ltrb_amodal[..., 2:3],
  167. topk_ys * 1.0 + ltrb_amodal[..., 3:4]
  168. ],
  169. axis=1)
  170. ret['bboxes'] = paddle.concat([bboxes[:, 0:2], bboxes_amodal], 1)
  171. # cls_id, score, x0, y0, x1, y1
  172. return ret
  173. def centertrack_post_process(self, dets, meta, out_thresh):
  174. if not ('bboxes' in dets):
  175. return [{}]
  176. preds = []
  177. c, s = meta['center'].numpy(), meta['scale'].numpy()
  178. h, w = meta['out_height'].numpy(), meta['out_width'].numpy()
  179. trans = get_affine_transform(
  180. center=c[0],
  181. input_size=s[0],
  182. rot=0,
  183. output_size=[w[0], h[0]],
  184. shift=(0., 0.),
  185. inv=True).astype(np.float32)
  186. for i, dets_bbox in enumerate(dets['bboxes']):
  187. if dets_bbox[1] < out_thresh:
  188. break
  189. item = {}
  190. item['score'] = dets_bbox[1]
  191. item['class'] = int(dets_bbox[0]) + 1
  192. item['ct'] = transform_preds_with_trans(
  193. dets['cts'][i].reshape([1, 2]), trans).reshape(2)
  194. if 'tracking' in dets:
  195. tracking = transform_preds_with_trans(
  196. (dets['tracking'][i] + dets['cts'][i]).reshape([1, 2]),
  197. trans).reshape(2)
  198. item['tracking'] = tracking - item['ct']
  199. if 'bboxes' in dets:
  200. bbox = transform_preds_with_trans(
  201. dets_bbox[2:6].reshape([2, 2]), trans).reshape(4)
  202. item['bbox'] = bbox
  203. preds.append(item)
  204. return preds
  205. def transform_preds_with_trans(coords, trans):
  206. target_coords = np.ones((coords.shape[0], 3), np.float32)
  207. target_coords[:, :2] = coords
  208. target_coords = np.dot(trans, target_coords.transpose()).transpose()
  209. return target_coords[:, :2]
  210. def _tranpose_and_gather_feat(feat, bbox_inds):
  211. feat = feat.transpose([0, 2, 3, 1])
  212. feat = feat.reshape([-1, feat.shape[3]])
  213. feat = paddle.gather(feat, bbox_inds)
  214. return feat