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.1 kB

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