test_operators.py 9.4 KB

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