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

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