test_operators.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. def _is_seg(sample):
  93. return 'mask' in sample and 'image2' not in sample
  94. def _is_det(sample):
  95. return 'gt_bbox' in sample or 'gt_poly' in sample
  96. def _is_clas(sample):
  97. return 'label' in sample
  98. _filter_only_optical = _InputFilter([_is_optical])
  99. _filter_only_sar = _InputFilter([_is_sar])
  100. _filter_only_multispectral = _InputFilter([_is_multispectral])
  101. _filter_no_multispectral = _filter_only_optical | _filter_only_sar
  102. _filter_no_sar = _filter_only_optical | _filter_only_multispectral
  103. _filter_no_optical = _filter_only_sar | _filter_only_multispectral
  104. _filter_only_mt = _InputFilter([_is_mt])
  105. _filter_no_det = _InputFilter([_is_seg, _is_clas, _is_mt])
  106. OP2FILTER = {
  107. 'RandomSwap': _filter_only_mt,
  108. 'SelectBand': _filter_no_sar,
  109. 'Dehaze': _filter_only_optical,
  110. 'Normalize': _filter_only_optical,
  111. 'RandomDistort': _filter_only_optical
  112. }
  113. @_add_op_tests
  114. class TestTransform(CpuCommonTest):
  115. def setUp(self):
  116. self.inputs = [
  117. build_input_from_file(
  118. "data/ssst/test_optical_clas.txt",
  119. prefix="./data/ssst"),
  120. build_input_from_file(
  121. "data/ssst/test_sar_clas.txt",
  122. prefix="./data/ssst"),
  123. build_input_from_file(
  124. "data/ssst/test_multispectral_clas.txt",
  125. prefix="./data/ssst"),
  126. build_input_from_file(
  127. "data/ssst/test_optical_seg.txt",
  128. prefix="./data/ssst"),
  129. build_input_from_file(
  130. "data/ssst/test_sar_seg.txt",
  131. prefix="./data/ssst"),
  132. build_input_from_file(
  133. "data/ssst/test_multispectral_seg.txt",
  134. prefix="./data/ssst"),
  135. build_input_from_file(
  136. "data/ssst/test_optical_det.txt",
  137. prefix="./data/ssst",
  138. label_list="data/ssst/labels_det.txt"),
  139. build_input_from_file(
  140. "data/ssst/test_sar_det.txt",
  141. prefix="./data/ssst",
  142. label_list="data/ssst/labels_det.txt"),
  143. build_input_from_file(
  144. "data/ssst/test_multispectral_det.txt",
  145. prefix="./data/ssst",
  146. label_list="data/ssst/labels_det.txt"),
  147. build_input_from_file(
  148. "data/ssst/test_det_coco.txt",
  149. prefix="./data/ssst"),
  150. build_input_from_file(
  151. "data/ssmt/test_mixed_binary.txt",
  152. prefix="./data/ssmt"),
  153. build_input_from_file(
  154. "data/ssmt/test_mixed_multiclass.txt",
  155. prefix="./data/ssmt"),
  156. build_input_from_file(
  157. "data/ssmt/test_mixed_multitask.txt",
  158. prefix="./data/ssmt")
  159. ] # yapf: disable
  160. def test_DecodeImg(self):
  161. decoder = T.DecodeImg(to_rgb=True)
  162. for i, input in enumerate(self.inputs):
  163. with self.subTest(i=i):
  164. for sample in input:
  165. sample = decoder(sample)
  166. # Check type
  167. self.assertIsInstance(sample['image'], np.ndarray)
  168. if 'mask' in sample:
  169. self.assertIsInstance(sample['mask'], np.ndarray)
  170. if 'aux_masks' in sample:
  171. for aux_mask in sample['aux_masks']:
  172. self.assertIsInstance(aux_mask, np.ndarray)
  173. # TODO: Check dtype
  174. def test_Resize(self):
  175. TARGET_SIZE = (128, 128)
  176. def _in_hook(sample):
  177. self.image_shape = sample['image'].shape
  178. if 'mask' in sample:
  179. self.mask_shape = sample['mask'].shape
  180. self.mask_values = set(sample['mask'].ravel())
  181. if 'aux_masks' in sample:
  182. self.aux_mask_shapes = [
  183. aux_mask.shape for aux_mask in sample['aux_masks']
  184. ]
  185. self.aux_mask_values = [
  186. set(aux_mask.ravel()) for aux_mask in sample['aux_masks']
  187. ]
  188. return sample
  189. def _out_hook_not_keep_ratio(sample):
  190. self.check_output_equal(sample['image'].shape[:2], TARGET_SIZE)
  191. if 'image2' in sample:
  192. self.check_output_equal(sample['image2'].shape[:2], TARGET_SIZE)
  193. if 'mask' in sample:
  194. self.check_output_equal(sample['mask'].shape[:2], TARGET_SIZE)
  195. self.assertLessEqual(
  196. set(sample['mask'].ravel()), self.mask_values)
  197. if 'aux_masks' in sample:
  198. for aux_mask in sample['aux_masks']:
  199. self.check_output_equal(aux_mask.shape[:2], TARGET_SIZE)
  200. for aux_mask, amv in zip(sample['aux_masks'],
  201. self.aux_mask_values):
  202. self.assertLessEqual(set(aux_mask.ravel()), amv)
  203. # TODO: Test gt_bbox and gt_poly
  204. return sample
  205. def _out_hook_keep_ratio(sample):
  206. def __check_ratio(shape1, shape2):
  207. self.check_output_equal(shape1[0] / shape1[1],
  208. shape2[0] / shape2[1])
  209. __check_ratio(sample['image'].shape, self.image_shape)
  210. if 'image2' in sample:
  211. __check_ratio(sample['image2'].shape, self.image_shape)
  212. if 'mask' in sample:
  213. __check_ratio(sample['mask'].shape, self.mask_shape)
  214. if 'aux_masks' in sample:
  215. for aux_mask, ori_aux_mask_shape in zip(sample['aux_masks'],
  216. self.aux_mask_shapes):
  217. __check_ratio(aux_mask.shape, ori_aux_mask_shape)
  218. # TODO: Test gt_bbox and gt_poly
  219. return sample
  220. test_func_not_keep_ratio = make_test_func(
  221. T.Resize,
  222. in_hook=_in_hook,
  223. out_hook=_out_hook_not_keep_ratio,
  224. target_size=TARGET_SIZE,
  225. keep_ratio=False)
  226. test_func_not_keep_ratio(self)
  227. test_func_keep_ratio = make_test_func(
  228. T.Resize,
  229. in_hook=_in_hook,
  230. out_hook=_out_hook_keep_ratio,
  231. target_size=TARGET_SIZE,
  232. keep_ratio=True)
  233. test_func_keep_ratio(self)
  234. def test_RandomFlipOrRotate(self):
  235. def _in_hook(sample):
  236. if 'image2' in sample:
  237. self.im_diff = (
  238. sample['image'] - sample['image2']).astype('float64')
  239. elif 'mask' in sample:
  240. self.im_diff = (
  241. sample['image'][..., 0] - sample['mask']).astype('float64')
  242. return sample
  243. def _out_hook(sample):
  244. im_diff = None
  245. if 'image2' in sample:
  246. im_diff = (sample['image'] - sample['image2']).astype('float64')
  247. elif 'mask' in sample:
  248. im_diff = (
  249. sample['image'][..., 0] - sample['mask']).astype('float64')
  250. if im_diff is not None:
  251. self.check_output_equal(im_diff.max(), self.im_diff.max())
  252. self.check_output_equal(im_diff.min(), self.im_diff.min())
  253. return sample
  254. test_func = make_test_func(
  255. T.RandomFlipOrRotate,
  256. in_hook=_in_hook,
  257. out_hook=_out_hook,
  258. filter_=_filter_no_det)
  259. test_func(self)
  260. class TestCompose(CpuCommonTest):
  261. pass
  262. class TestArrange(CpuCommonTest):
  263. pass