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

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