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

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