test_operators.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. task='seg',
  132. prefix="./data/ssst"),
  133. build_input_from_file(
  134. "data/ssst/test_sar_seg.txt",
  135. task='seg',
  136. prefix="./data/ssst"),
  137. build_input_from_file(
  138. "data/ssst/test_multispectral_seg.txt",
  139. task='seg',
  140. prefix="./data/ssst"),
  141. build_input_from_file(
  142. "data/ssst/test_optical_det.txt",
  143. prefix="./data/ssst",
  144. label_list="data/ssst/labels_det.txt"),
  145. build_input_from_file(
  146. "data/ssst/test_sar_det.txt",
  147. prefix="./data/ssst",
  148. label_list="data/ssst/labels_det.txt"),
  149. build_input_from_file(
  150. "data/ssst/test_multispectral_det.txt",
  151. prefix="./data/ssst",
  152. label_list="data/ssst/labels_det.txt"),
  153. build_input_from_file(
  154. "data/ssst/test_det_coco.txt",
  155. task='det',
  156. prefix="./data/ssst"),
  157. build_input_from_file(
  158. "data/ssst/test_optical_res.txt",
  159. task='res',
  160. prefix="./data/ssst",
  161. sr_factor=4),
  162. build_input_from_file(
  163. "data/ssst/test_sar_res.txt",
  164. task='res',
  165. prefix="./data/ssst",
  166. sr_factor=4),
  167. build_input_from_file(
  168. "data/ssst/test_multispectral_res.txt",
  169. task='res',
  170. prefix="./data/ssst",
  171. sr_factor=4),
  172. build_input_from_file(
  173. "data/ssmt/test_mixed_binary.txt",
  174. prefix="./data/ssmt"),
  175. build_input_from_file(
  176. "data/ssmt/test_mixed_multiclass.txt",
  177. prefix="./data/ssmt"),
  178. build_input_from_file(
  179. "data/ssmt/test_mixed_multitask.txt",
  180. prefix="./data/ssmt")
  181. ] # yapf: disable
  182. def test_DecodeImg(self):
  183. decoder = T.DecodeImg(to_rgb=True)
  184. for i, input in enumerate(self.inputs):
  185. with self.subTest(i=i):
  186. for sample in input:
  187. sample = decoder(sample)
  188. # Check type
  189. self.assertIsInstance(sample['image'], np.ndarray)
  190. if 'mask' in sample:
  191. self.assertIsInstance(sample['mask'], np.ndarray)
  192. if 'aux_masks' in sample:
  193. for aux_mask in sample['aux_masks']:
  194. self.assertIsInstance(aux_mask, np.ndarray)
  195. # TODO: Check dtype
  196. def test_Resize(self):
  197. TARGET_SIZE = (128, 128)
  198. def _in_hook(sample):
  199. self.image_shape = sample['image'].shape
  200. if 'mask' in sample:
  201. self.mask_shape = sample['mask'].shape
  202. self.mask_values = set(sample['mask'].ravel())
  203. if 'aux_masks' in sample:
  204. self.aux_mask_shapes = [
  205. aux_mask.shape for aux_mask in sample['aux_masks']
  206. ]
  207. self.aux_mask_values = [
  208. set(aux_mask.ravel()) for aux_mask in sample['aux_masks']
  209. ]
  210. if 'target' in sample:
  211. self.target_shape = sample['target'].shape
  212. return sample
  213. def _out_hook_not_keep_ratio(sample):
  214. self.check_output_equal(sample['image'].shape[:2], TARGET_SIZE)
  215. if 'image2' in sample:
  216. self.check_output_equal(sample['image2'].shape[:2], TARGET_SIZE)
  217. if 'mask' in sample:
  218. self.check_output_equal(sample['mask'].shape[:2], TARGET_SIZE)
  219. self.assertLessEqual(
  220. set(sample['mask'].ravel()), self.mask_values)
  221. if 'aux_masks' in sample:
  222. for aux_mask in sample['aux_masks']:
  223. self.check_output_equal(aux_mask.shape[:2], TARGET_SIZE)
  224. for aux_mask, amv in zip(sample['aux_masks'],
  225. self.aux_mask_values):
  226. self.assertLessEqual(set(aux_mask.ravel()), amv)
  227. if 'target' in sample:
  228. if 'sr_factor' in sample:
  229. self.check_output_equal(
  230. sample['target'].shape[:2],
  231. T.functions.calc_hr_shape(TARGET_SIZE,
  232. sample['sr_factor']))
  233. else:
  234. self.check_output_equal(sample['target'].shape[:2],
  235. TARGET_SIZE)
  236. self.check_output_equal(
  237. sample['target'].shape[0] / self.target_shape[0],
  238. sample['image'].shape[0] / self.image_shape[0])
  239. self.check_output_equal(
  240. sample['target'].shape[1] / self.target_shape[1],
  241. sample['image'].shape[1] / self.image_shape[1])
  242. # TODO: Test gt_bbox and gt_poly
  243. return sample
  244. def _out_hook_keep_ratio(sample):
  245. def __check_ratio(shape1, shape2):
  246. self.check_output_equal(shape1[0] / shape1[1],
  247. shape2[0] / shape2[1])
  248. __check_ratio(sample['image'].shape, self.image_shape)
  249. if 'image2' in sample:
  250. __check_ratio(sample['image2'].shape, self.image_shape)
  251. if 'mask' in sample:
  252. __check_ratio(sample['mask'].shape, self.mask_shape)
  253. if 'aux_masks' in sample:
  254. for aux_mask, ori_aux_mask_shape in zip(sample['aux_masks'],
  255. self.aux_mask_shapes):
  256. __check_ratio(aux_mask.shape, ori_aux_mask_shape)
  257. if 'target' in sample:
  258. self.check_output_equal(
  259. sample['target'].shape[0] / self.target_shape[0],
  260. sample['image'].shape[0] / self.image_shape[0])
  261. self.check_output_equal(
  262. sample['target'].shape[1] / self.target_shape[1],
  263. sample['image'].shape[1] / self.image_shape[1])
  264. # TODO: Test gt_bbox and gt_poly
  265. return sample
  266. test_func_not_keep_ratio = make_test_func(
  267. T.Resize,
  268. _in_hook=_in_hook,
  269. _out_hook=_out_hook_not_keep_ratio,
  270. target_size=TARGET_SIZE,
  271. keep_ratio=False)
  272. test_func_not_keep_ratio(self)
  273. test_func_keep_ratio = make_test_func(
  274. T.Resize,
  275. _in_hook=_in_hook,
  276. _out_hook=_out_hook_keep_ratio,
  277. target_size=TARGET_SIZE,
  278. keep_ratio=True)
  279. test_func_keep_ratio(self)
  280. def test_RandomFlipOrRotate(self):
  281. def _in_hook(sample):
  282. if 'image2' in sample:
  283. self.im_diff = (
  284. sample['image'] - sample['image2']).astype('float64')
  285. elif 'mask' in sample:
  286. self.im_diff = (
  287. sample['image'][..., 0] - sample['mask']).astype('float64')
  288. return sample
  289. def _out_hook(sample):
  290. im_diff = None
  291. if 'image2' in sample:
  292. im_diff = (sample['image'] - sample['image2']).astype('float64')
  293. elif 'mask' in sample:
  294. im_diff = (
  295. sample['image'][..., 0] - sample['mask']).astype('float64')
  296. if im_diff is not None:
  297. self.check_output_equal(im_diff.max(), self.im_diff.max())
  298. self.check_output_equal(im_diff.min(), self.im_diff.min())
  299. return sample
  300. test_func = make_test_func(
  301. T.RandomFlipOrRotate,
  302. _in_hook=_in_hook,
  303. _out_hook=_out_hook,
  304. _filter=_filter_no_det)
  305. test_func(self)
  306. def test_AppendIndex(self):
  307. def _out_hook_ndvi(sample):
  308. self.check_output_equal(sample['image'].shape[2], 11)
  309. self.assertLessEqual(sample['image'][..., -1].max() - 1e-8, 1)
  310. self.assertGreaterEqual(sample['image'][..., -1].min() + 1e-8, -1)
  311. if 'image2' in sample:
  312. self.check_output_equal(sample['image2'].shape[2], 11)
  313. self.assertLessEqual(sample['image2'][..., -1].max() - 1e-8, 1)
  314. self.assertGreaterEqual(sample['image2'][..., -1].min() + 1e-8,
  315. -1)
  316. return sample
  317. test_ndvi = make_test_func(
  318. T.AppendIndex,
  319. 'NDVI', {'r': 1,
  320. 'n': 2},
  321. _out_hook=_out_hook_ndvi,
  322. _filter=_filter_only_multispectral)
  323. test_ndvi(self)
  324. test_evi = make_test_func(
  325. T.AppendIndex,
  326. 'EVI', {'b': 1,
  327. 'r': 2,
  328. 'n': 3},
  329. c0=1.0,
  330. c1=0.5,
  331. c2=1.0,
  332. c3=1.5,
  333. _filter=_filter_only_multispectral)
  334. test_evi(self)
  335. test_evi_from_satellite = make_test_func(
  336. T.AppendIndex,
  337. 'EVI',
  338. satellite='Landsat_89',
  339. c0=1.0,
  340. c1=0.5,
  341. c2=1.0,
  342. c3=1.5,
  343. _filter=_filter_only_multispectral)
  344. test_evi_from_satellite(self)
  345. def test_MatchRadiance(self):
  346. test_hist = make_test_func(
  347. T.MatchRadiance, 'hist', _filter=_filter_only_mt)
  348. test_hist(self)
  349. test_lsr = make_test_func(
  350. T.MatchRadiance, 'lsr', _filter=_filter_only_mt)
  351. test_lsr(self)
  352. class TestCompose(CpuCommonTest):
  353. pass
  354. class TestArrange(CpuCommonTest):
  355. pass