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 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. def test_random_affine_exception_shear_value():
  165. """
  166. Test RandomAffine: shear is a number but is not positive, expected to raise ValueError
  167. """
  168. logger.info("test_random_affine_exception_shear_value")
  169. try:
  170. _ = py_vision.RandomAffine(degrees=15, shear=-5)
  171. except ValueError as e:
  172. logger.info("Got an exception in DE: {}".format(str(e)))
  173. assert str(e) == "Input shear must be greater than 0."
  174. def test_random_affine_exception_degrees_size():
  175. """
  176. Test RandomAffine: degrees is a list or tuple and its length is not 2,
  177. expected to raise TypeError
  178. """
  179. logger.info("test_random_affine_exception_degrees_size")
  180. try:
  181. _ = py_vision.RandomAffine(degrees=[15])
  182. except TypeError as e:
  183. logger.info("Got an exception in DE: {}".format(str(e)))
  184. assert str(e) == "If degrees is a sequence, the length must be 2."
  185. def test_random_affine_exception_translate_size():
  186. """
  187. Test RandomAffine: translate is not list or a tuple of length 2,
  188. expected to raise TypeError
  189. """
  190. logger.info("test_random_affine_exception_translate_size")
  191. try:
  192. _ = py_vision.RandomAffine(degrees=15, translate=(0.1))
  193. except TypeError as e:
  194. logger.info("Got an exception in DE: {}".format(str(e)))
  195. assert str(
  196. e) == "Argument translate with value 0.1 is not of type (<class 'list'>," \
  197. " <class 'tuple'>)."
  198. def test_random_affine_exception_scale_size():
  199. """
  200. Test RandomAffine: scale is not a list or tuple of length 2,
  201. expected to raise TypeError
  202. """
  203. logger.info("test_random_affine_exception_scale_size")
  204. try:
  205. _ = py_vision.RandomAffine(degrees=15, scale=(0.5))
  206. except TypeError as e:
  207. logger.info("Got an exception in DE: {}".format(str(e)))
  208. assert str(e) == "Argument scale with value 0.5 is not of type (<class 'tuple'>," \
  209. " <class 'list'>)."
  210. def test_random_affine_exception_shear_size():
  211. """
  212. Test RandomAffine: shear is not a list or tuple of length 2 or 4,
  213. expected to raise TypeError
  214. """
  215. logger.info("test_random_affine_exception_shear_size")
  216. try:
  217. _ = py_vision.RandomAffine(degrees=15, shear=(-5, 5, 10))
  218. except TypeError as e:
  219. logger.info("Got an exception in DE: {}".format(str(e)))
  220. assert str(e) == "shear must be of length 2 or 4."
  221. if __name__ == "__main__":
  222. test_random_affine_op(plot=True)
  223. test_random_affine_op_c(plot=True)
  224. test_random_affine_md5()
  225. test_random_affine_c_md5()
  226. test_random_affine_exception_negative_degrees()
  227. test_random_affine_exception_translation_range()
  228. test_random_affine_exception_scale_value()
  229. test_random_affine_exception_shear_value()
  230. test_random_affine_exception_degrees_size()
  231. test_random_affine_exception_translate_size()
  232. test_random_affine_exception_scale_size()
  233. test_random_affine_exception_shear_size()