You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_random_affine.py 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ==============================================================================
  15. """
  16. Testing RandomAffine op in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.transforms.vision.py_transforms as py_vision
  21. import mindspore.dataset.transforms.vision.c_transforms as c_vision
  22. from mindspore import log as logger
  23. from util import visualize_list, save_and_check_md5, \
  24. config_get_set_seed, config_get_set_num_parallel_workers
  25. GENERATE_GOLDEN = False
  26. DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  27. SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
  28. def test_random_affine_op(plot=False):
  29. """
  30. Test RandomAffine in python transformations
  31. """
  32. logger.info("test_random_affine_op")
  33. # define map operations
  34. transforms1 = [
  35. py_vision.Decode(),
  36. py_vision.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.9, 1.1)),
  37. py_vision.ToTensor()
  38. ]
  39. transform1 = py_vision.ComposeOp(transforms1)
  40. transforms2 = [
  41. py_vision.Decode(),
  42. py_vision.ToTensor()
  43. ]
  44. transform2 = py_vision.ComposeOp(transforms2)
  45. # First dataset
  46. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  47. data1 = data1.map(input_columns=["image"], operations=transform1())
  48. # Second dataset
  49. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  50. data2 = data2.map(input_columns=["image"], operations=transform2())
  51. image_affine = []
  52. image_original = []
  53. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  54. image1 = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  55. image2 = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  56. image_affine.append(image1)
  57. image_original.append(image2)
  58. if plot:
  59. visualize_list(image_original, image_affine)
  60. def test_random_affine_op_c(plot=False):
  61. """
  62. Test RandomAffine in C transformations
  63. """
  64. logger.info("test_random_affine_op_c")
  65. # define map operations
  66. transforms1 = [
  67. c_vision.Decode(),
  68. c_vision.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.9, 1.1))
  69. ]
  70. transforms2 = [
  71. c_vision.Decode()
  72. ]
  73. # First dataset
  74. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  75. data1 = data1.map(input_columns=["image"], operations=transforms1)
  76. # Second dataset
  77. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  78. data2 = data2.map(input_columns=["image"], operations=transforms2)
  79. image_affine = []
  80. image_original = []
  81. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  82. image1 = item1["image"]
  83. image2 = item2["image"]
  84. image_affine.append(image1)
  85. image_original.append(image2)
  86. if plot:
  87. visualize_list(image_original, image_affine)
  88. def test_random_affine_md5():
  89. """
  90. Test RandomAffine with md5 comparison
  91. """
  92. logger.info("test_random_affine_md5")
  93. original_seed = config_get_set_seed(55)
  94. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  95. # define map operations
  96. transforms = [
  97. py_vision.Decode(),
  98. py_vision.RandomAffine(degrees=(-5, 15), translate=(0.1, 0.3),
  99. scale=(0.9, 1.1), shear=(-10, 10, -5, 5)),
  100. py_vision.ToTensor()
  101. ]
  102. transform = py_vision.ComposeOp(transforms)
  103. # Generate dataset
  104. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  105. data = data.map(input_columns=["image"], operations=transform())
  106. # check results with md5 comparison
  107. filename = "random_affine_01_result.npz"
  108. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  109. # Restore configuration
  110. ds.config.set_seed(original_seed)
  111. ds.config.set_num_parallel_workers((original_num_parallel_workers))
  112. def test_random_affine_c_md5():
  113. """
  114. Test RandomAffine C Op with md5 comparison
  115. """
  116. logger.info("test_random_affine_c_md5")
  117. original_seed = config_get_set_seed(1)
  118. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  119. # define map operations
  120. transforms = [
  121. c_vision.Decode(),
  122. c_vision.RandomAffine(degrees=(-5, 15), translate=(0.1, 0.3),
  123. scale=(0.9, 1.1), shear=(-10, 10, -5, 5))
  124. ]
  125. # Generate dataset
  126. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  127. data = data.map(input_columns=["image"], operations=transforms)
  128. # check results with md5 comparison
  129. filename = "random_affine_01_c_result.npz"
  130. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  131. # Restore configuration
  132. ds.config.set_seed(original_seed)
  133. ds.config.set_num_parallel_workers((original_num_parallel_workers))
  134. def test_random_affine_exception_negative_degrees():
  135. """
  136. Test RandomAffine: input degrees in negative, expected to raise ValueError
  137. """
  138. logger.info("test_random_affine_exception_negative_degrees")
  139. try:
  140. _ = py_vision.RandomAffine(degrees=-15)
  141. except ValueError as e:
  142. logger.info("Got an exception in DE: {}".format(str(e)))
  143. assert str(e) == "Input degrees is not within the required interval of (0 to inf)."
  144. def test_random_affine_exception_translation_range():
  145. """
  146. Test RandomAffine: translation value is not in [0, 1], expected to raise ValueError
  147. """
  148. logger.info("test_random_affine_exception_translation_range")
  149. try:
  150. _ = py_vision.RandomAffine(degrees=15, translate=(0.1, 1.5))
  151. except ValueError as e:
  152. logger.info("Got an exception in DE: {}".format(str(e)))
  153. assert str(e) == "Input translate at 1 is not within the required interval of (0.0 to 1.0)."
  154. def test_random_affine_exception_scale_value():
  155. """
  156. Test RandomAffine: scale is not positive, expected to raise ValueError
  157. """
  158. logger.info("test_random_affine_exception_scale_value")
  159. try:
  160. _ = py_vision.RandomAffine(degrees=15, scale=(0.0, 1.1))
  161. except ValueError as e:
  162. logger.info("Got an exception in DE: {}".format(str(e)))
  163. assert str(e) == "Input scale[0] must be greater than 0."
  164. try:
  165. _ = py_vision.RandomAffine(degrees=15, scale=(2.0, 1.1))
  166. except ValueError as e:
  167. logger.info("Got an exception in DE: {}".format(str(e)))
  168. assert str(e) == "Input scale[1] must be equal to or greater than scale[0]."
  169. def test_random_affine_exception_shear_value():
  170. """
  171. Test RandomAffine: shear is a number but is not positive, expected to raise ValueError
  172. """
  173. logger.info("test_random_affine_exception_shear_value")
  174. try:
  175. _ = py_vision.RandomAffine(degrees=15, shear=-5)
  176. except ValueError as e:
  177. logger.info("Got an exception in DE: {}".format(str(e)))
  178. assert str(e) == "Input shear must be greater than 0."
  179. try:
  180. _ = py_vision.RandomAffine(degrees=15, shear=(5, 1))
  181. except ValueError as e:
  182. logger.info("Got an exception in DE: {}".format(str(e)))
  183. assert str(e) == "Input shear[1] must be equal to or greater than shear[0]"
  184. try:
  185. _ = py_vision.RandomAffine(degrees=15, shear=(5, 1, 2, 8))
  186. except ValueError as e:
  187. logger.info("Got an exception in DE: {}".format(str(e)))
  188. assert str(e) == "Input shear[1] must be equal to or greater than shear[0] and " \
  189. "shear[3] must be equal to or greater than shear[2]."
  190. try:
  191. _ = py_vision.RandomAffine(degrees=15, shear=(5, 9, 2, 1))
  192. except ValueError as e:
  193. logger.info("Got an exception in DE: {}".format(str(e)))
  194. assert str(e) == "Input shear[1] must be equal to or greater than shear[0] and " \
  195. "shear[3] must be equal to or greater than shear[2]."
  196. def test_random_affine_exception_degrees_size():
  197. """
  198. Test RandomAffine: degrees is a list or tuple and its length is not 2,
  199. expected to raise TypeError
  200. """
  201. logger.info("test_random_affine_exception_degrees_size")
  202. try:
  203. _ = py_vision.RandomAffine(degrees=[15])
  204. except TypeError as e:
  205. logger.info("Got an exception in DE: {}".format(str(e)))
  206. assert str(e) == "If degrees is a sequence, the length must be 2."
  207. def test_random_affine_exception_translate_size():
  208. """
  209. Test RandomAffine: translate is not list or a tuple of length 2,
  210. expected to raise TypeError
  211. """
  212. logger.info("test_random_affine_exception_translate_size")
  213. try:
  214. _ = py_vision.RandomAffine(degrees=15, translate=(0.1))
  215. except TypeError as e:
  216. logger.info("Got an exception in DE: {}".format(str(e)))
  217. assert str(
  218. e) == "Argument translate with value 0.1 is not of type (<class 'list'>," \
  219. " <class 'tuple'>)."
  220. def test_random_affine_exception_scale_size():
  221. """
  222. Test RandomAffine: scale is not a list or tuple of length 2,
  223. expected to raise TypeError
  224. """
  225. logger.info("test_random_affine_exception_scale_size")
  226. try:
  227. _ = py_vision.RandomAffine(degrees=15, scale=(0.5))
  228. except TypeError as e:
  229. logger.info("Got an exception in DE: {}".format(str(e)))
  230. assert str(e) == "Argument scale with value 0.5 is not of type (<class 'tuple'>," \
  231. " <class 'list'>)."
  232. def test_random_affine_exception_shear_size():
  233. """
  234. Test RandomAffine: shear is not a list or tuple of length 2 or 4,
  235. expected to raise TypeError
  236. """
  237. logger.info("test_random_affine_exception_shear_size")
  238. try:
  239. _ = py_vision.RandomAffine(degrees=15, shear=(-5, 5, 10))
  240. except TypeError as e:
  241. logger.info("Got an exception in DE: {}".format(str(e)))
  242. assert str(e) == "shear must be of length 2 or 4."
  243. if __name__ == "__main__":
  244. test_random_affine_op(plot=True)
  245. test_random_affine_op_c(plot=True)
  246. test_random_affine_md5()
  247. test_random_affine_c_md5()
  248. test_random_affine_exception_negative_degrees()
  249. test_random_affine_exception_translation_range()
  250. test_random_affine_exception_scale_value()
  251. test_random_affine_exception_shear_value()
  252. test_random_affine_exception_degrees_size()
  253. test_random_affine_exception_translate_size()
  254. test_random_affine_exception_scale_size()
  255. test_random_affine_exception_shear_size()