test_operators.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 inspect
  15. import copy
  16. import numpy as np
  17. import paddlers.transforms as T
  18. from testing_utils import CpuCommonTest
  19. from data import build_input_from_file
  20. __all__ = ['TestTransform', 'TestCompose', 'TestArrange']
  21. WHITE_LIST = ['ReloadMask']
  22. def _add_op_tests(cls):
  23. """
  24. Automatically patch testing functions for transform operators.
  25. """
  26. for op_name in T.operators.__all__:
  27. op_class = getattr(T.operators, op_name)
  28. if isinstance(op_class, type) and issubclass(op_class,
  29. T.operators.Transform):
  30. if op_class is T.DecodeImg or op_class in WHITE_LIST or op_name in WHITE_LIST:
  31. continue
  32. if issubclass(op_class, T.Compose) or issubclass(
  33. op_class, T.operators.Arrange):
  34. continue
  35. attr_name = 'test_' + op_name
  36. if hasattr(cls, attr_name):
  37. continue
  38. # If the operator cannot be initialized with default parameters, skip it.
  39. for key, param in inspect.signature(
  40. op_class.__init__).parameters.items():
  41. if key == 'self':
  42. continue
  43. if param.default is param.empty:
  44. break
  45. else:
  46. filter_ = OP2FILTER.get(op_name, None)
  47. setattr(
  48. cls, attr_name, make_test_func(
  49. op_class, filter_=filter_))
  50. return cls
  51. def make_test_func(op_class,
  52. *args,
  53. in_hook=None,
  54. out_hook=None,
  55. filter_=None,
  56. **kwargs):
  57. def _test_func(self):
  58. op = op_class(*args, **kwargs)
  59. decoder = T.DecodeImg()
  60. inputs = map(decoder, copy.deepcopy(self.inputs))
  61. for i, input_ in enumerate(inputs):
  62. if filter_ is not None:
  63. input_ = filter_(input_)
  64. with self.subTest(i=i):
  65. for sample in input_:
  66. if in_hook:
  67. sample = in_hook(sample)
  68. sample = op(sample)
  69. if out_hook:
  70. sample = out_hook(sample)
  71. return _test_func
  72. class _InputFilter(object):
  73. def __init__(self, conds):
  74. self.conds = conds
  75. def __call__(self, samples):
  76. for sample in samples:
  77. for cond in self.conds:
  78. if cond(sample):
  79. yield sample
  80. def __or__(self, filter):
  81. return _InputFilter(self.conds + filter.conds)
  82. def __and__(self, filter):
  83. return _InputFilter(
  84. [cond for cond in self.conds if cond in filter.conds])
  85. def get_sample(self, input):
  86. return input[0]
  87. def _is_optical(sample):
  88. return sample['image'].shape[2] == 3
  89. def _is_sar(sample):
  90. return sample['image'].shape[2] == 1
  91. def _is_multispectral(sample):
  92. return sample['image'].shape[2] > 3
  93. def _is_mt(sample):
  94. return 'image2' in sample
  95. def _is_seg(sample):
  96. return 'mask' in sample and 'image2' not in sample
  97. def _is_det(sample):
  98. return 'gt_bbox' in sample or 'gt_poly' in sample
  99. def _is_clas(sample):
  100. return 'label' in sample
  101. _filter_only_optical = _InputFilter([_is_optical])
  102. _filter_only_sar = _InputFilter([_is_sar])
  103. _filter_only_multispectral = _InputFilter([_is_multispectral])
  104. _filter_no_multispectral = _filter_only_optical | _filter_only_sar
  105. _filter_no_sar = _filter_only_optical | _filter_only_multispectral
  106. _filter_no_optical = _filter_only_sar | _filter_only_multispectral
  107. _filter_only_mt = _InputFilter([_is_mt])
  108. _filter_no_det = _InputFilter([_is_seg, _is_clas, _is_mt])
  109. OP2FILTER = {
  110. 'RandomSwap': _filter_only_mt,
  111. 'SelectBand': _filter_no_sar,
  112. 'Dehaze': _filter_only_optical,
  113. 'Normalize': _filter_only_optical,
  114. 'RandomDistort': _filter_only_optical
  115. }
  116. @_add_op_tests
  117. class TestTransform(CpuCommonTest):
  118. def setUp(self):
  119. self.inputs = [
  120. build_input_from_file(
  121. "data/ssst/test_optical_clas.txt",
  122. prefix="./data/ssst"),
  123. build_input_from_file(
  124. "data/ssst/test_sar_clas.txt",
  125. prefix="./data/ssst"),
  126. build_input_from_file(
  127. "data/ssst/test_multispectral_clas.txt",
  128. prefix="./data/ssst"),
  129. build_input_from_file(
  130. "data/ssst/test_optical_seg.txt",
  131. prefix="./data/ssst"),
  132. build_input_from_file(
  133. "data/ssst/test_sar_seg.txt",
  134. prefix="./data/ssst"),
  135. build_input_from_file(
  136. "data/ssst/test_multispectral_seg.txt",
  137. prefix="./data/ssst"),
  138. build_input_from_file(
  139. "data/ssst/test_optical_det.txt",
  140. prefix="./data/ssst",
  141. label_list="data/ssst/labels_det.txt"),
  142. build_input_from_file(
  143. "data/ssst/test_sar_det.txt",
  144. prefix="./data/ssst",
  145. label_list="data/ssst/labels_det.txt"),
  146. build_input_from_file(
  147. "data/ssst/test_multispectral_det.txt",
  148. prefix="./data/ssst",
  149. label_list="data/ssst/labels_det.txt"),
  150. build_input_from_file(
  151. "data/ssst/test_det_coco.txt",
  152. prefix="./data/ssst"),
  153. build_input_from_file(
  154. "data/ssmt/test_mixed_binary.txt",
  155. prefix="./data/ssmt"),
  156. build_input_from_file(
  157. "data/ssmt/test_mixed_multiclass.txt",
  158. prefix="./data/ssmt"),
  159. build_input_from_file(
  160. "data/ssmt/test_mixed_multitask.txt",
  161. prefix="./data/ssmt")
  162. ] # yapf: disable
  163. def test_DecodeImg(self):
  164. decoder = T.DecodeImg(to_rgb=True)
  165. for i, input in enumerate(self.inputs):
  166. with self.subTest(i=i):
  167. for sample in input:
  168. sample = decoder(sample)
  169. # Check type
  170. self.assertIsInstance(sample['image'], np.ndarray)
  171. if 'mask' in sample:
  172. self.assertIsInstance(sample['mask'], np.ndarray)
  173. if 'aux_masks' in sample:
  174. for aux_mask in sample['aux_masks']:
  175. self.assertIsInstance(aux_mask, np.ndarray)
  176. # TODO: Check dtype
  177. def test_Resize(self):
  178. TARGET_SIZE = (128, 128)
  179. def _in_hook(sample):
  180. self.image_shape = sample['image'].shape
  181. if 'mask' in sample:
  182. self.mask_shape = sample['mask'].shape
  183. self.mask_values = set(sample['mask'].ravel())
  184. if 'aux_masks' in sample:
  185. self.aux_mask_shapes = [
  186. aux_mask.shape for aux_mask in sample['aux_masks']
  187. ]
  188. self.aux_mask_values = [
  189. set(aux_mask.ravel()) for aux_mask in sample['aux_masks']
  190. ]
  191. return sample
  192. def _out_hook_not_keep_ratio(sample):
  193. self.check_output_equal(sample['image'].shape[:2], TARGET_SIZE)
  194. if 'image2' in sample:
  195. self.check_output_equal(sample['image2'].shape[:2], TARGET_SIZE)
  196. if 'mask' in sample:
  197. self.check_output_equal(sample['mask'].shape[:2], TARGET_SIZE)
  198. self.assertLessEqual(
  199. set(sample['mask'].ravel()), self.mask_values)
  200. if 'aux_masks' in sample:
  201. for aux_mask in sample['aux_masks']:
  202. self.check_output_equal(aux_mask.shape[:2], TARGET_SIZE)
  203. for aux_mask, amv in zip(sample['aux_masks'],
  204. self.aux_mask_values):
  205. self.assertLessEqual(set(aux_mask.ravel()), amv)
  206. # TODO: Test gt_bbox and gt_poly
  207. return sample
  208. def _out_hook_keep_ratio(sample):
  209. def __check_ratio(shape1, shape2):
  210. self.check_output_equal(shape1[0] / shape1[1],
  211. shape2[0] / shape2[1])
  212. __check_ratio(sample['image'].shape, self.image_shape)
  213. if 'image2' in sample:
  214. __check_ratio(sample['image2'].shape, self.image_shape)
  215. if 'mask' in sample:
  216. __check_ratio(sample['mask'].shape, self.mask_shape)
  217. if 'aux_masks' in sample:
  218. for aux_mask, ori_aux_mask_shape in zip(sample['aux_masks'],
  219. self.aux_mask_shapes):
  220. __check_ratio(aux_mask.shape, ori_aux_mask_shape)
  221. # TODO: Test gt_bbox and gt_poly
  222. return sample
  223. test_func_not_keep_ratio = make_test_func(
  224. T.Resize,
  225. in_hook=_in_hook,
  226. out_hook=_out_hook_not_keep_ratio,
  227. target_size=TARGET_SIZE,
  228. keep_ratio=False)
  229. test_func_not_keep_ratio(self)
  230. test_func_keep_ratio = make_test_func(
  231. T.Resize,
  232. in_hook=_in_hook,
  233. out_hook=_out_hook_keep_ratio,
  234. target_size=TARGET_SIZE,
  235. keep_ratio=True)
  236. test_func_keep_ratio(self)
  237. def test_RandomFlipOrRotate(self):
  238. def _in_hook(sample):
  239. if 'image2' in sample:
  240. self.im_diff = (
  241. sample['image'] - sample['image2']).astype('float64')
  242. elif 'mask' in sample:
  243. self.im_diff = (
  244. sample['image'][..., 0] - sample['mask']).astype('float64')
  245. return sample
  246. def _out_hook(sample):
  247. im_diff = None
  248. if 'image2' in sample:
  249. im_diff = (sample['image'] - sample['image2']).astype('float64')
  250. elif 'mask' in sample:
  251. im_diff = (
  252. sample['image'][..., 0] - sample['mask']).astype('float64')
  253. if im_diff is not None:
  254. self.check_output_equal(im_diff.max(), self.im_diff.max())
  255. self.check_output_equal(im_diff.min(), self.im_diff.min())
  256. return sample
  257. test_func = make_test_func(
  258. T.RandomFlipOrRotate,
  259. in_hook=_in_hook,
  260. out_hook=_out_hook,
  261. filter_=_filter_no_det)
  262. test_func(self)
  263. class TestCompose(CpuCommonTest):
  264. pass
  265. class TestArrange(CpuCommonTest):
  266. pass