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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  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=0, translate=(0.5, 0.5, 0, 0))
  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(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  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.1, -0.3, 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_default_c_md5():
  136. """
  137. Test RandomAffine C Op (default params) with md5 comparison
  138. """
  139. logger.info("test_random_affine_default_c_md5")
  140. original_seed = config_get_set_seed(1)
  141. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  142. # define map operations
  143. transforms = [
  144. c_vision.Decode(),
  145. c_vision.RandomAffine(degrees=0)
  146. ]
  147. # Generate dataset
  148. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  149. data = data.map(input_columns=["image"], operations=transforms)
  150. # check results with md5 comparison
  151. filename = "random_affine_01_default_c_result.npz"
  152. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  153. # Restore configuration
  154. ds.config.set_seed(original_seed)
  155. ds.config.set_num_parallel_workers((original_num_parallel_workers))
  156. def test_random_affine_py_exception_non_pil_images():
  157. """
  158. Test RandomAffine: input img is ndarray and not PIL, expected to raise RuntimeError
  159. """
  160. logger.info("test_random_affine_exception_negative_degrees")
  161. dataset = ds.MnistDataset(MNIST_DATA_DIR, num_parallel_workers=3)
  162. try:
  163. transform = py_vision.ComposeOp([py_vision.ToTensor(),
  164. py_vision.RandomAffine(degrees=(15, 15))])
  165. dataset = dataset.map(input_columns=["image"], operations=transform(), num_parallel_workers=3,
  166. python_multiprocessing=True)
  167. for _ in dataset.create_dict_iterator(num_epochs=1):
  168. break
  169. except RuntimeError as e:
  170. logger.info("Got an exception in DE: {}".format(str(e)))
  171. assert "Pillow image" in str(e)
  172. def test_random_affine_exception_negative_degrees():
  173. """
  174. Test RandomAffine: input degrees in negative, expected to raise ValueError
  175. """
  176. logger.info("test_random_affine_exception_negative_degrees")
  177. try:
  178. _ = py_vision.RandomAffine(degrees=-15)
  179. except ValueError as e:
  180. logger.info("Got an exception in DE: {}".format(str(e)))
  181. assert str(e) == "Input degrees is not within the required interval of (0 to inf)."
  182. def test_random_affine_exception_translation_range():
  183. """
  184. Test RandomAffine: translation value is not in [-1, 1], expected to raise ValueError
  185. """
  186. logger.info("test_random_affine_exception_translation_range")
  187. try:
  188. _ = c_vision.RandomAffine(degrees=15, translate=(0.1, 1.5))
  189. except ValueError as e:
  190. logger.info("Got an exception in DE: {}".format(str(e)))
  191. assert str(e) == "Input translate at 1 is not within the required interval of (-1.0 to 1.0)."
  192. logger.info("test_random_affine_exception_translation_range")
  193. try:
  194. _ = c_vision.RandomAffine(degrees=15, translate=(-2, 1.5))
  195. except ValueError as e:
  196. logger.info("Got an exception in DE: {}".format(str(e)))
  197. assert str(e) == "Input translate at 0 is not within the required interval of (-1.0 to 1.0)."
  198. def test_random_affine_exception_scale_value():
  199. """
  200. Test RandomAffine: scale is not positive, expected to raise ValueError
  201. """
  202. logger.info("test_random_affine_exception_scale_value")
  203. try:
  204. _ = py_vision.RandomAffine(degrees=15, scale=(0.0, 1.1))
  205. except ValueError as e:
  206. logger.info("Got an exception in DE: {}".format(str(e)))
  207. assert str(e) == "Input scale[0] must be greater than 0."
  208. try:
  209. _ = py_vision.RandomAffine(degrees=15, scale=(2.0, 1.1))
  210. except ValueError as e:
  211. logger.info("Got an exception in DE: {}".format(str(e)))
  212. assert str(e) == "Input scale[1] must be equal to or greater than scale[0]."
  213. def test_random_affine_exception_shear_value():
  214. """
  215. Test RandomAffine: shear is a number but is not positive, expected to raise ValueError
  216. """
  217. logger.info("test_random_affine_exception_shear_value")
  218. try:
  219. _ = py_vision.RandomAffine(degrees=15, shear=-5)
  220. except ValueError as e:
  221. logger.info("Got an exception in DE: {}".format(str(e)))
  222. assert str(e) == "Input shear must be greater than 0."
  223. try:
  224. _ = py_vision.RandomAffine(degrees=15, shear=(5, 1))
  225. except ValueError as e:
  226. logger.info("Got an exception in DE: {}".format(str(e)))
  227. assert str(e) == "Input shear[1] must be equal to or greater than shear[0]"
  228. try:
  229. _ = py_vision.RandomAffine(degrees=15, shear=(5, 1, 2, 8))
  230. except ValueError as e:
  231. logger.info("Got an exception in DE: {}".format(str(e)))
  232. assert str(e) == "Input shear[1] must be equal to or greater than shear[0] and " \
  233. "shear[3] must be equal to or greater than shear[2]."
  234. try:
  235. _ = py_vision.RandomAffine(degrees=15, shear=(5, 9, 2, 1))
  236. except ValueError as e:
  237. logger.info("Got an exception in DE: {}".format(str(e)))
  238. assert str(e) == "Input shear[1] must be equal to or greater than shear[0] and " \
  239. "shear[3] must be equal to or greater than shear[2]."
  240. def test_random_affine_exception_degrees_size():
  241. """
  242. Test RandomAffine: degrees is a list or tuple and its length is not 2,
  243. expected to raise TypeError
  244. """
  245. logger.info("test_random_affine_exception_degrees_size")
  246. try:
  247. _ = py_vision.RandomAffine(degrees=[15])
  248. except TypeError as e:
  249. logger.info("Got an exception in DE: {}".format(str(e)))
  250. assert str(e) == "If degrees is a sequence, the length must be 2."
  251. def test_random_affine_exception_translate_size():
  252. """
  253. Test RandomAffine: translate is not list or a tuple of length 2,
  254. expected to raise TypeError
  255. """
  256. logger.info("test_random_affine_exception_translate_size")
  257. try:
  258. _ = py_vision.RandomAffine(degrees=15, translate=(0.1))
  259. except TypeError as e:
  260. logger.info("Got an exception in DE: {}".format(str(e)))
  261. assert str(
  262. e) == "Argument translate with value 0.1 is not of type (<class 'list'>," \
  263. " <class 'tuple'>)."
  264. def test_random_affine_exception_scale_size():
  265. """
  266. Test RandomAffine: scale is not a list or tuple of length 2,
  267. expected to raise TypeError
  268. """
  269. logger.info("test_random_affine_exception_scale_size")
  270. try:
  271. _ = py_vision.RandomAffine(degrees=15, scale=(0.5))
  272. except TypeError as e:
  273. logger.info("Got an exception in DE: {}".format(str(e)))
  274. assert str(e) == "Argument scale with value 0.5 is not of type (<class 'tuple'>," \
  275. " <class 'list'>)."
  276. def test_random_affine_exception_shear_size():
  277. """
  278. Test RandomAffine: shear is not a list or tuple of length 2 or 4,
  279. expected to raise TypeError
  280. """
  281. logger.info("test_random_affine_exception_shear_size")
  282. try:
  283. _ = py_vision.RandomAffine(degrees=15, shear=(-5, 5, 10))
  284. except TypeError as e:
  285. logger.info("Got an exception in DE: {}".format(str(e)))
  286. assert str(e) == "shear must be of length 2 or 4."
  287. if __name__ == "__main__":
  288. test_random_affine_op(plot=True)
  289. test_random_affine_op_c(plot=True)
  290. test_random_affine_md5()
  291. test_random_affine_c_md5()
  292. test_random_affine_default_c_md5()
  293. test_random_affine_py_exception_non_pil_images()
  294. test_random_affine_exception_negative_degrees()
  295. test_random_affine_exception_translation_range()
  296. test_random_affine_exception_scale_value()
  297. test_random_affine_exception_shear_value()
  298. test_random_affine_exception_degrees_size()
  299. test_random_affine_exception_translate_size()
  300. test_random_affine_exception_scale_size()
  301. test_random_affine_exception_shear_size()