test_operators.py 9.3 KB

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