strongsort.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from typing import Optional
  3. import numpy as np
  4. from mmengine.structures import InstanceData
  5. from torch import Tensor
  6. from mmdet.registry import MODELS, TASK_UTILS
  7. from mmdet.structures import TrackSampleList
  8. from mmdet.utils import OptConfigType
  9. from .deep_sort import DeepSORT
  10. @MODELS.register_module()
  11. class StrongSORT(DeepSORT):
  12. """StrongSORT: Make DeepSORT Great Again.
  13. Details can be found at `StrongSORT<https://arxiv.org/abs/2202.13514>`_.
  14. Args:
  15. detector (dict): Configuration of detector. Defaults to None.
  16. reid (dict): Configuration of reid. Defaults to None
  17. tracker (dict): Configuration of tracker. Defaults to None.
  18. kalman (dict): Configuration of Kalman filter. Defaults to None.
  19. cmc (dict): Configuration of camera model compensation.
  20. Defaults to None.
  21. data_preprocessor (dict or ConfigDict, optional): The pre-process
  22. config of :class:`TrackDataPreprocessor`. it usually includes,
  23. ``pad_size_divisor``, ``pad_value``, ``mean`` and ``std``.
  24. init_cfg (dict or list[dict]): Configuration of initialization.
  25. Defaults to None.
  26. """
  27. def __init__(self,
  28. detector: Optional[dict] = None,
  29. reid: Optional[dict] = None,
  30. cmc: Optional[dict] = None,
  31. tracker: Optional[dict] = None,
  32. postprocess_model: Optional[dict] = None,
  33. data_preprocessor: OptConfigType = None,
  34. init_cfg: OptConfigType = None):
  35. super().__init__(detector, reid, tracker, data_preprocessor, init_cfg)
  36. if cmc is not None:
  37. self.cmc = TASK_UTILS.build(cmc)
  38. if postprocess_model is not None:
  39. self.postprocess_model = TASK_UTILS.build(postprocess_model)
  40. @property
  41. def with_cmc(self):
  42. """bool: whether the framework has a camera model compensation
  43. model.
  44. """
  45. return hasattr(self, 'cmc') and self.cmc is not None
  46. def predict(self,
  47. inputs: Tensor,
  48. data_samples: TrackSampleList,
  49. rescale: bool = True,
  50. **kwargs) -> TrackSampleList:
  51. """Predict results from a video and data samples with post- processing.
  52. Args:
  53. inputs (Tensor): of shape (N, T, C, H, W) encoding
  54. input images. The N denotes batch size.
  55. The T denotes the number of key frames
  56. and reference frames.
  57. data_samples (list[:obj:`TrackDataSample`]): The batch
  58. data samples. It usually includes information such
  59. as `gt_instance`.
  60. rescale (bool, Optional): If False, then returned bboxes and masks
  61. will fit the scale of img, otherwise, returned bboxes and masks
  62. will fit the scale of original image shape. Defaults to True.
  63. Returns:
  64. TrackSampleList: List[TrackDataSample]
  65. Tracking results of the input videos.
  66. Each DetDataSample usually contains ``pred_track_instances``.
  67. """
  68. assert inputs.dim() == 5, 'The img must be 5D Tensor (N, T, C, H, W).'
  69. assert inputs.size(0) == 1, \
  70. 'SORT/DeepSORT inference only support ' \
  71. '1 batch size per gpu for now.'
  72. assert len(data_samples) == 1, \
  73. 'SORT/DeepSORT inference only support ' \
  74. '1 batch size per gpu for now.'
  75. track_data_sample = data_samples[0]
  76. video_len = len(track_data_sample)
  77. video_track_instances = []
  78. for frame_id in range(video_len):
  79. img_data_sample = track_data_sample[frame_id]
  80. single_img = inputs[:, frame_id].contiguous()
  81. # det_results List[DetDataSample]
  82. det_results = self.detector.predict(single_img, [img_data_sample])
  83. assert len(det_results) == 1, 'Batch inference is not supported.'
  84. pred_track_instances = self.tracker.track(
  85. model=self,
  86. img=single_img,
  87. data_sample=det_results[0],
  88. data_preprocessor=self.preprocess_cfg,
  89. rescale=rescale,
  90. **kwargs)
  91. for i in range(len(pred_track_instances.instances_id)):
  92. video_track_instances.append(
  93. np.array([
  94. frame_id + 1,
  95. pred_track_instances.instances_id[i].cpu(),
  96. pred_track_instances.bboxes[i][0].cpu(),
  97. pred_track_instances.bboxes[i][1].cpu(),
  98. (pred_track_instances.bboxes[i][2] -
  99. pred_track_instances.bboxes[i][0]).cpu(),
  100. (pred_track_instances.bboxes[i][3] -
  101. pred_track_instances.bboxes[i][1]).cpu(),
  102. pred_track_instances.scores[i].cpu()
  103. ]))
  104. video_track_instances = np.array(video_track_instances).reshape(-1, 7)
  105. video_track_instances = self.postprocess_model.forward(
  106. video_track_instances)
  107. for frame_id in range(video_len):
  108. track_data_sample[frame_id].pred_track_instances = \
  109. InstanceData(bboxes=video_track_instances[
  110. video_track_instances[:, 0] == frame_id + 1, :])
  111. return [track_data_sample]