wrappers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import copy
  3. from typing import Callable, Dict, List, Optional, Union
  4. import numpy as np
  5. from mmcv.transforms import BaseTransform, Compose
  6. from mmcv.transforms.utils import cache_random_params, cache_randomness
  7. from mmdet.registry import TRANSFORMS
  8. @TRANSFORMS.register_module()
  9. class MultiBranch(BaseTransform):
  10. r"""Multiple branch pipeline wrapper.
  11. Generate multiple data-augmented versions of the same image.
  12. `MultiBranch` needs to specify the branch names of all
  13. pipelines of the dataset, perform corresponding data augmentation
  14. for the current branch, and return None for other branches,
  15. which ensures the consistency of return format across
  16. different samples.
  17. Args:
  18. branch_field (list): List of branch names.
  19. branch_pipelines (dict): Dict of different pipeline configs
  20. to be composed.
  21. Examples:
  22. >>> branch_field = ['sup', 'unsup_teacher', 'unsup_student']
  23. >>> sup_pipeline = [
  24. >>> dict(type='LoadImageFromFile'),
  25. >>> dict(type='LoadAnnotations', with_bbox=True),
  26. >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True),
  27. >>> dict(type='RandomFlip', prob=0.5),
  28. >>> dict(
  29. >>> type='MultiBranch',
  30. >>> branch_field=branch_field,
  31. >>> sup=dict(type='PackDetInputs'))
  32. >>> ]
  33. >>> weak_pipeline = [
  34. >>> dict(type='LoadImageFromFile'),
  35. >>> dict(type='LoadAnnotations', with_bbox=True),
  36. >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True),
  37. >>> dict(type='RandomFlip', prob=0.0),
  38. >>> dict(
  39. >>> type='MultiBranch',
  40. >>> branch_field=branch_field,
  41. >>> sup=dict(type='PackDetInputs'))
  42. >>> ]
  43. >>> strong_pipeline = [
  44. >>> dict(type='LoadImageFromFile'),
  45. >>> dict(type='LoadAnnotations', with_bbox=True),
  46. >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True),
  47. >>> dict(type='RandomFlip', prob=1.0),
  48. >>> dict(
  49. >>> type='MultiBranch',
  50. >>> branch_field=branch_field,
  51. >>> sup=dict(type='PackDetInputs'))
  52. >>> ]
  53. >>> unsup_pipeline = [
  54. >>> dict(type='LoadImageFromFile'),
  55. >>> dict(type='LoadEmptyAnnotations'),
  56. >>> dict(
  57. >>> type='MultiBranch',
  58. >>> branch_field=branch_field,
  59. >>> unsup_teacher=weak_pipeline,
  60. >>> unsup_student=strong_pipeline)
  61. >>> ]
  62. >>> from mmcv.transforms import Compose
  63. >>> sup_branch = Compose(sup_pipeline)
  64. >>> unsup_branch = Compose(unsup_pipeline)
  65. >>> print(sup_branch)
  66. >>> Compose(
  67. >>> LoadImageFromFile(ignore_empty=False, to_float32=False, color_type='color', imdecode_backend='cv2') # noqa
  68. >>> LoadAnnotations(with_bbox=True, with_label=True, with_mask=False, with_seg=False, poly2mask=True, imdecode_backend='cv2') # noqa
  69. >>> Resize(scale=(1333, 800), scale_factor=None, keep_ratio=True, clip_object_border=True), backend=cv2), interpolation=bilinear) # noqa
  70. >>> RandomFlip(prob=0.5, direction=horizontal)
  71. >>> MultiBranch(branch_pipelines=['sup'])
  72. >>> )
  73. >>> print(unsup_branch)
  74. >>> Compose(
  75. >>> LoadImageFromFile(ignore_empty=False, to_float32=False, color_type='color', imdecode_backend='cv2') # noqa
  76. >>> LoadEmptyAnnotations(with_bbox=True, with_label=True, with_mask=False, with_seg=False, seg_ignore_label=255) # noqa
  77. >>> MultiBranch(branch_pipelines=['unsup_teacher', 'unsup_student'])
  78. >>> )
  79. """
  80. def __init__(self, branch_field: List[str],
  81. **branch_pipelines: dict) -> None:
  82. self.branch_field = branch_field
  83. self.branch_pipelines = {
  84. branch: Compose(pipeline)
  85. for branch, pipeline in branch_pipelines.items()
  86. }
  87. def transform(self, results: dict) -> dict:
  88. """Transform function to apply transforms sequentially.
  89. Args:
  90. results (dict): Result dict from loading pipeline.
  91. Returns:
  92. dict:
  93. - 'inputs' (Dict[str, obj:`torch.Tensor`]): The forward data of
  94. models from different branches.
  95. - 'data_sample' (Dict[str,obj:`DetDataSample`]): The annotation
  96. info of the sample from different branches.
  97. """
  98. multi_results = {}
  99. for branch in self.branch_field:
  100. multi_results[branch] = {'inputs': None, 'data_samples': None}
  101. for branch, pipeline in self.branch_pipelines.items():
  102. branch_results = pipeline(copy.deepcopy(results))
  103. # If one branch pipeline returns None,
  104. # it will sample another data from dataset.
  105. if branch_results is None:
  106. return None
  107. multi_results[branch] = branch_results
  108. format_results = {}
  109. for branch, results in multi_results.items():
  110. for key in results.keys():
  111. if format_results.get(key, None) is None:
  112. format_results[key] = {branch: results[key]}
  113. else:
  114. format_results[key][branch] = results[key]
  115. return format_results
  116. def __repr__(self) -> str:
  117. repr_str = self.__class__.__name__
  118. repr_str += f'(branch_pipelines={list(self.branch_pipelines.keys())})'
  119. return repr_str
  120. @TRANSFORMS.register_module()
  121. class RandomOrder(Compose):
  122. """Shuffle the transform Sequence."""
  123. @cache_randomness
  124. def _random_permutation(self):
  125. return np.random.permutation(len(self.transforms))
  126. def transform(self, results: Dict) -> Optional[Dict]:
  127. """Transform function to apply transforms in random order.
  128. Args:
  129. results (dict): A result dict contains the results to transform.
  130. Returns:
  131. dict or None: Transformed results.
  132. """
  133. inds = self._random_permutation()
  134. for idx in inds:
  135. t = self.transforms[idx]
  136. results = t(results)
  137. if results is None:
  138. return None
  139. return results
  140. def __repr__(self):
  141. """Compute the string representation."""
  142. format_string = self.__class__.__name__ + '('
  143. for t in self.transforms:
  144. format_string += f'{t.__class__.__name__}, '
  145. format_string += ')'
  146. return format_string
  147. @TRANSFORMS.register_module()
  148. class ProposalBroadcaster(BaseTransform):
  149. """A transform wrapper to apply the wrapped transforms to process both
  150. `gt_bboxes` and `proposals` without adding any codes. It will do the
  151. following steps:
  152. 1. Scatter the broadcasting targets to a list of inputs of the wrapped
  153. transforms. The type of the list should be list[dict, dict], which
  154. the first is the original inputs, the second is the processing
  155. results that `gt_bboxes` being rewritten by the `proposals`.
  156. 2. Apply ``self.transforms``, with same random parameters, which is
  157. sharing with a context manager. The type of the outputs is a
  158. list[dict, dict].
  159. 3. Gather the outputs, update the `proposals` in the first item of
  160. the outputs with the `gt_bboxes` in the second .
  161. Args:
  162. transforms (list, optional): Sequence of transform
  163. object or config dict to be wrapped. Defaults to [].
  164. Note: The `TransformBroadcaster` in MMCV can achieve the same operation as
  165. `ProposalBroadcaster`, but need to set more complex parameters.
  166. Examples:
  167. >>> pipeline = [
  168. >>> dict(type='LoadImageFromFile'),
  169. >>> dict(type='LoadProposals', num_max_proposals=2000),
  170. >>> dict(type='LoadAnnotations', with_bbox=True),
  171. >>> dict(
  172. >>> type='ProposalBroadcaster',
  173. >>> transforms=[
  174. >>> dict(type='Resize', scale=(1333, 800),
  175. >>> keep_ratio=True),
  176. >>> dict(type='RandomFlip', prob=0.5),
  177. >>> ]),
  178. >>> dict(type='PackDetInputs')]
  179. """
  180. def __init__(self, transforms: List[Union[dict, Callable]] = []) -> None:
  181. self.transforms = Compose(transforms)
  182. def transform(self, results: dict) -> dict:
  183. """Apply wrapped transform functions to process both `gt_bboxes` and
  184. `proposals`.
  185. Args:
  186. results (dict): Result dict from loading pipeline.
  187. Returns:
  188. dict: Updated result dict.
  189. """
  190. assert results.get('proposals', None) is not None, \
  191. '`proposals` should be in the results, please delete ' \
  192. '`ProposalBroadcaster` in your configs, or check whether ' \
  193. 'you have load proposals successfully.'
  194. inputs = self._process_input(results)
  195. outputs = self._apply_transforms(inputs)
  196. outputs = self._process_output(outputs)
  197. return outputs
  198. def _process_input(self, data: dict) -> list:
  199. """Scatter the broadcasting targets to a list of inputs of the wrapped
  200. transforms.
  201. Args:
  202. data (dict): The original input data.
  203. Returns:
  204. list[dict]: A list of input data.
  205. """
  206. cp_data = copy.deepcopy(data)
  207. cp_data['gt_bboxes'] = cp_data['proposals']
  208. scatters = [data, cp_data]
  209. return scatters
  210. def _apply_transforms(self, inputs: list) -> list:
  211. """Apply ``self.transforms``.
  212. Args:
  213. inputs (list[dict, dict]): list of input data.
  214. Returns:
  215. list[dict]: The output of the wrapped pipeline.
  216. """
  217. assert len(inputs) == 2
  218. ctx = cache_random_params
  219. with ctx(self.transforms):
  220. output_scatters = [self.transforms(_input) for _input in inputs]
  221. return output_scatters
  222. def _process_output(self, output_scatters: list) -> dict:
  223. """Gathering and renaming data items.
  224. Args:
  225. output_scatters (list[dict, dict]): The output of the wrapped
  226. pipeline.
  227. Returns:
  228. dict: Updated result dict.
  229. """
  230. assert isinstance(output_scatters, list) and \
  231. isinstance(output_scatters[0], dict) and \
  232. len(output_scatters) == 2
  233. outputs = output_scatters[0]
  234. outputs['proposals'] = output_scatters[1]['gt_bboxes']
  235. return outputs