test_operators.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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'),
  112. build_input_from_file(
  113. 'data/ssst/test_sar_clas.txt',
  114. prefix='./data/ssst'),
  115. build_input_from_file(
  116. 'data/ssst/test_multispectral_clas.txt',
  117. prefix='./data/ssst'),
  118. build_input_from_file(
  119. 'data/ssst/test_optical_seg.txt',
  120. prefix='./data/ssst'),
  121. build_input_from_file(
  122. 'data/ssst/test_sar_seg.txt',
  123. prefix='./data/ssst'),
  124. build_input_from_file(
  125. 'data/ssst/test_multispectral_seg.txt',
  126. prefix='./data/ssst'),
  127. build_input_from_file(
  128. 'data/ssst/test_optical_det.txt',
  129. prefix='./data/ssst',
  130. label_list='data/ssst/labels_det.txt'),
  131. build_input_from_file(
  132. 'data/ssst/test_sar_det.txt',
  133. prefix='./data/ssst',
  134. label_list='data/ssst/labels_det.txt'),
  135. build_input_from_file(
  136. 'data/ssst/test_multispectral_det.txt',
  137. prefix='./data/ssst',
  138. label_list='data/ssst/labels_det.txt'),
  139. build_input_from_file(
  140. 'data/ssmt/test_mixed_binary.txt',
  141. prefix='./data/ssmt'),
  142. build_input_from_file(
  143. 'data/ssmt/test_mixed_multiclass.txt',
  144. prefix='./data/ssmt'),
  145. build_input_from_file(
  146. 'data/ssmt/test_mixed_multitask.txt',
  147. prefix='./data/ssmt')
  148. ]
  149. def test_DecodeImg(self):
  150. decoder = T.DecodeImg(to_rgb=True)
  151. for i, input in enumerate(self.inputs):
  152. with self.subTest(i=i):
  153. for sample in input:
  154. sample = decoder(sample)
  155. # Check type
  156. self.assertIsInstance(sample['image'], np.ndarray)
  157. if 'mask' in sample:
  158. self.assertIsInstance(sample['mask'], np.ndarray)
  159. if 'aux_masks' in sample:
  160. for aux_mask in sample['aux_masks']:
  161. self.assertIsInstance(aux_mask, np.ndarray)
  162. # TODO: Check dtype
  163. def test_Resize(self):
  164. TARGET_SIZE = (128, 128)
  165. def _in_hook(sample):
  166. self.image_shape = sample['image'].shape
  167. if 'mask' in sample:
  168. self.mask_shape = sample['mask'].shape
  169. self.mask_values = set(sample['mask'].ravel())
  170. if 'aux_masks' in sample:
  171. self.aux_mask_shapes = [
  172. aux_mask.shape for aux_mask in sample['aux_masks']
  173. ]
  174. self.aux_mask_values = [
  175. set(aux_mask.ravel()) for aux_mask in sample['aux_masks']
  176. ]
  177. return sample
  178. def _out_hook_not_keep_ratio(sample):
  179. self.check_output_equal(sample['image'].shape[:2], TARGET_SIZE)
  180. if 'image2' in sample:
  181. self.check_output_equal(sample['image2'].shape[:2], TARGET_SIZE)
  182. if 'mask' in sample:
  183. self.check_output_equal(sample['mask'].shape[:2], TARGET_SIZE)
  184. self.assertLessEqual(
  185. set(sample['mask'].ravel()), self.mask_values)
  186. if 'aux_masks' in sample:
  187. for aux_mask in sample['aux_masks']:
  188. self.check_output_equal(aux_mask.shape[:2], TARGET_SIZE)
  189. for aux_mask, amv in zip(sample['aux_masks'],
  190. self.aux_mask_values):
  191. self.assertLessEqual(set(aux_mask.ravel()), amv)
  192. # TODO: Test gt_bbox and gt_poly
  193. return sample
  194. def _out_hook_keep_ratio(sample):
  195. def __check_ratio(shape1, shape2):
  196. self.check_output_equal(shape1[0] / shape1[1],
  197. shape2[0] / shape2[1])
  198. __check_ratio(sample['image'].shape, self.image_shape)
  199. if 'image2' in sample:
  200. __check_ratio(sample['image2'].shape, self.image_shape)
  201. if 'mask' in sample:
  202. __check_ratio(sample['mask'].shape, self.mask_shape)
  203. if 'aux_masks' in sample:
  204. for aux_mask, ori_aux_mask_shape in zip(sample['aux_masks'],
  205. self.aux_mask_shapes):
  206. __check_ratio(aux_mask.shape, ori_aux_mask_shape)
  207. # TODO: Test gt_bbox and gt_poly
  208. return sample
  209. test_func_not_keep_ratio = make_test_func(
  210. T.Resize,
  211. in_hook=_in_hook,
  212. out_hook=_out_hook_not_keep_ratio,
  213. target_size=TARGET_SIZE,
  214. keep_ratio=False)
  215. test_func_not_keep_ratio(self)
  216. test_func_keep_ratio = make_test_func(
  217. T.Resize,
  218. in_hook=_in_hook,
  219. out_hook=_out_hook_keep_ratio,
  220. target_size=TARGET_SIZE,
  221. keep_ratio=True)
  222. test_func_keep_ratio(self)
  223. class TestCompose(CpuCommonTest):
  224. pass
  225. class TestArrange(CpuCommonTest):
  226. pass