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_vertical_flip.py 8.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # Copyright 2019 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 the random vertical flip 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.c_transforms as c_vision
  22. import mindspore.dataset.vision.py_transforms as py_vision
  23. from mindspore import log as logger
  24. from util import save_and_check_md5, visualize_list, visualize_image, diff_mse, \
  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. def v_flip(image):
  30. """
  31. Apply the random_vertical
  32. """
  33. # with the seed provided in this test case, it will always flip.
  34. # that's why we flip here too
  35. image = image[::-1, :, :]
  36. return image
  37. def test_random_vertical_op(plot=False):
  38. """
  39. Test random_vertical with default probability
  40. """
  41. logger.info("Test random_vertical")
  42. # First dataset
  43. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  44. decode_op = c_vision.Decode()
  45. random_vertical_op = c_vision.RandomVerticalFlip(1.0)
  46. data1 = data1.map(operations=decode_op, input_columns=["image"])
  47. data1 = data1.map(operations=random_vertical_op, input_columns=["image"])
  48. # Second dataset
  49. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  50. data2 = data2.map(operations=decode_op, input_columns=["image"])
  51. num_iter = 0
  52. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  53. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  54. # with the seed value, we can only guarantee the first number generated
  55. if num_iter > 0:
  56. break
  57. image_v_flipped = item1["image"]
  58. image = item2["image"]
  59. image_v_flipped_2 = v_flip(image)
  60. mse = diff_mse(image_v_flipped, image_v_flipped_2)
  61. assert mse == 0
  62. logger.info("image_{}, mse: {}".format(num_iter + 1, mse))
  63. num_iter += 1
  64. if plot:
  65. visualize_image(image, image_v_flipped, mse, image_v_flipped_2)
  66. def test_random_vertical_valid_prob_c():
  67. """
  68. Test RandomVerticalFlip op with c_transforms: valid non-default input, expect to pass
  69. """
  70. logger.info("test_random_vertical_valid_prob_c")
  71. original_seed = config_get_set_seed(0)
  72. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  73. # Generate dataset
  74. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  75. decode_op = c_vision.Decode()
  76. random_horizontal_op = c_vision.RandomVerticalFlip(0.8)
  77. data = data.map(operations=decode_op, input_columns=["image"])
  78. data = data.map(operations=random_horizontal_op, input_columns=["image"])
  79. filename = "random_vertical_01_c_result.npz"
  80. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  81. # Restore config setting
  82. ds.config.set_seed(original_seed)
  83. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  84. def test_random_vertical_valid_prob_py():
  85. """
  86. Test RandomVerticalFlip op with py_transforms: valid non-default input, expect to pass
  87. """
  88. logger.info("test_random_vertical_valid_prob_py")
  89. original_seed = config_get_set_seed(0)
  90. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  91. # Generate dataset
  92. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  93. transforms = [
  94. py_vision.Decode(),
  95. py_vision.RandomVerticalFlip(0.8),
  96. py_vision.ToTensor()
  97. ]
  98. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  99. data = data.map(operations=transform, input_columns=["image"])
  100. filename = "random_vertical_01_py_result.npz"
  101. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  102. # Restore config setting
  103. ds.config.set_seed(original_seed)
  104. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  105. def test_random_vertical_invalid_prob_c():
  106. """
  107. Test RandomVerticalFlip op in c_transforms: invalid input, expect to raise error
  108. """
  109. logger.info("test_random_vertical_invalid_prob_c")
  110. # Generate dataset
  111. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  112. decode_op = c_vision.Decode()
  113. try:
  114. # Note: Valid range of prob should be [0.0, 1.0]
  115. random_horizontal_op = c_vision.RandomVerticalFlip(1.5)
  116. data = data.map(operations=decode_op, input_columns=["image"])
  117. data = data.map(operations=random_horizontal_op, input_columns=["image"])
  118. except ValueError as e:
  119. logger.info("Got an exception in DE: {}".format(str(e)))
  120. assert 'Input prob is not within the required interval of [0.0, 1.0].' in str(e)
  121. def test_random_vertical_invalid_prob_py():
  122. """
  123. Test RandomVerticalFlip op in py_transforms: invalid input, expect to raise error
  124. """
  125. logger.info("test_random_vertical_invalid_prob_py")
  126. # Generate dataset
  127. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  128. try:
  129. transforms = [
  130. py_vision.Decode(),
  131. # Note: Valid range of prob should be [0.0, 1.0]
  132. py_vision.RandomVerticalFlip(1.5),
  133. py_vision.ToTensor()
  134. ]
  135. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  136. data = data.map(operations=transform, input_columns=["image"])
  137. except ValueError as e:
  138. logger.info("Got an exception in DE: {}".format(str(e)))
  139. assert 'Input prob is not within the required interval of [0.0, 1.0].' in str(e)
  140. def test_random_vertical_comp(plot=False):
  141. """
  142. Test test_random_vertical_flip and compare between python and c image augmentation ops
  143. """
  144. logger.info("test_random_vertical_comp")
  145. # First dataset
  146. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  147. decode_op = c_vision.Decode()
  148. # Note: The image must be flipped if prob is set to be 1
  149. random_horizontal_op = c_vision.RandomVerticalFlip(1)
  150. data1 = data1.map(operations=decode_op, input_columns=["image"])
  151. data1 = data1.map(operations=random_horizontal_op, input_columns=["image"])
  152. # Second dataset
  153. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  154. transforms = [
  155. py_vision.Decode(),
  156. # Note: The image must be flipped if prob is set to be 1
  157. py_vision.RandomVerticalFlip(1),
  158. py_vision.ToTensor()
  159. ]
  160. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  161. data2 = data2.map(operations=transform, input_columns=["image"])
  162. images_list_c = []
  163. images_list_py = []
  164. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  165. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  166. image_c = item1["image"]
  167. image_py = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  168. images_list_c.append(image_c)
  169. images_list_py.append(image_py)
  170. # Check if the output images are the same
  171. mse = diff_mse(image_c, image_py)
  172. assert mse < 0.001
  173. if plot:
  174. visualize_list(images_list_c, images_list_py, visualize_mode=2)
  175. if __name__ == "__main__":
  176. test_random_vertical_op(plot=True)
  177. test_random_vertical_valid_prob_c()
  178. test_random_vertical_valid_prob_py()
  179. test_random_vertical_invalid_prob_c()
  180. test_random_vertical_invalid_prob_py()
  181. test_random_vertical_comp(plot=True)