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

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