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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 matplotlib.pyplot as plt
  19. import numpy as np
  20. import mindspore.dataset as ds
  21. import mindspore.dataset.transforms.vision.c_transforms as c_vision
  22. import mindspore.dataset.transforms.vision.py_transforms as py_vision
  23. from mindspore import log as logger
  24. from util import save_and_check_md5, visualize, 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 visualize_with_mse(image_de_random_vertical, image_pil_random_vertical, mse, image_original):
  38. """
  39. visualizes the image using DE op and Numpy op
  40. """
  41. plt.subplot(141)
  42. plt.imshow(image_original)
  43. plt.title("Original image")
  44. plt.subplot(142)
  45. plt.imshow(image_de_random_vertical)
  46. plt.title("DE random_vertical image")
  47. plt.subplot(143)
  48. plt.imshow(image_pil_random_vertical)
  49. plt.title("vertically flipped image")
  50. plt.subplot(144)
  51. plt.imshow(image_de_random_vertical - image_pil_random_vertical)
  52. plt.title("Difference image, mse : {}".format(mse))
  53. plt.show()
  54. def test_random_vertical_op():
  55. """
  56. Test random_vertical with default probability
  57. """
  58. logger.info("Test random_vertical")
  59. # First dataset
  60. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  61. decode_op = c_vision.Decode()
  62. random_vertical_op = c_vision.RandomVerticalFlip()
  63. data1 = data1.map(input_columns=["image"], operations=decode_op)
  64. data1 = data1.map(input_columns=["image"], operations=random_vertical_op)
  65. # Second dataset
  66. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  67. data2 = data2.map(input_columns=["image"], operations=decode_op)
  68. num_iter = 0
  69. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  70. # with the seed value, we can only guarantee the first number generated
  71. if num_iter > 0:
  72. break
  73. image_v_flipped = item1["image"]
  74. image = item2["image"]
  75. image_v_flipped_2 = v_flip(image)
  76. diff = image_v_flipped - image_v_flipped_2
  77. mse = np.sum(np.power(diff, 2))
  78. logger.info("image_{}, mse: {}".format(num_iter + 1, mse))
  79. # Uncomment below line if you want to visualize images
  80. # visualize_with_mse(image_v_flipped, image_v_flipped_2, mse, image)
  81. num_iter += 1
  82. def test_random_vertical_valid_prob_c():
  83. """
  84. Test RandomVerticalFlip op with c_transforms: valid non-default input, expect to pass
  85. """
  86. logger.info("test_random_vertical_valid_prob_c")
  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. decode_op = c_vision.Decode()
  92. random_horizontal_op = c_vision.RandomVerticalFlip(0.8)
  93. data = data.map(input_columns=["image"], operations=decode_op)
  94. data = data.map(input_columns=["image"], operations=random_horizontal_op)
  95. filename = "random_vertical_01_c_result.npz"
  96. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  97. # Restore config setting
  98. ds.config.set_seed(original_seed)
  99. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  100. def test_random_vertical_valid_prob_py():
  101. """
  102. Test RandomVerticalFlip op with py_transforms: valid non-default input, expect to pass
  103. """
  104. logger.info("test_random_vertical_valid_prob_py")
  105. original_seed = config_get_set_seed(0)
  106. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  107. # Generate dataset
  108. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  109. transforms = [
  110. py_vision.Decode(),
  111. py_vision.RandomVerticalFlip(0.8),
  112. py_vision.ToTensor()
  113. ]
  114. transform = py_vision.ComposeOp(transforms)
  115. data = data.map(input_columns=["image"], operations=transform())
  116. filename = "random_vertical_01_py_result.npz"
  117. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  118. # Restore config setting
  119. ds.config.set_seed(original_seed)
  120. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  121. def test_random_vertical_invalid_prob_c():
  122. """
  123. Test RandomVerticalFlip op in c_transforms: invalid input, expect to raise error
  124. """
  125. logger.info("test_random_vertical_invalid_prob_c")
  126. # Generate dataset
  127. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  128. decode_op = c_vision.Decode()
  129. try:
  130. # Note: Valid range of prob should be [0.0, 1.0]
  131. random_horizontal_op = c_vision.RandomVerticalFlip(1.5)
  132. data = data.map(input_columns=["image"], operations=decode_op)
  133. data = data.map(input_columns=["image"], operations=random_horizontal_op)
  134. except ValueError as e:
  135. logger.info("Got an exception in DE: {}".format(str(e)))
  136. assert "Input is not" in str(e)
  137. def test_random_vertical_invalid_prob_py():
  138. """
  139. Test RandomVerticalFlip op in py_transforms: invalid input, expect to raise error
  140. """
  141. logger.info("test_random_vertical_invalid_prob_py")
  142. # Generate dataset
  143. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  144. try:
  145. transforms = [
  146. py_vision.Decode(),
  147. # Note: Valid range of prob should be [0.0, 1.0]
  148. py_vision.RandomVerticalFlip(1.5),
  149. py_vision.ToTensor()
  150. ]
  151. transform = py_vision.ComposeOp(transforms)
  152. data = data.map(input_columns=["image"], operations=transform())
  153. except ValueError as e:
  154. logger.info("Got an exception in DE: {}".format(str(e)))
  155. assert "Input is not" in str(e)
  156. def test_random_vertical_comp(plot=False):
  157. """
  158. Test test_random_vertical_flip and compare between python and c image augmentation ops
  159. """
  160. logger.info("test_random_vertical_comp")
  161. # First dataset
  162. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  163. decode_op = c_vision.Decode()
  164. # Note: The image must be flipped if prob is set to be 1
  165. random_horizontal_op = c_vision.RandomVerticalFlip(1)
  166. data1 = data1.map(input_columns=["image"], operations=decode_op)
  167. data1 = data1.map(input_columns=["image"], operations=random_horizontal_op)
  168. # Second dataset
  169. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  170. transforms = [
  171. py_vision.Decode(),
  172. # Note: The image must be flipped if prob is set to be 1
  173. py_vision.RandomVerticalFlip(1),
  174. py_vision.ToTensor()
  175. ]
  176. transform = py_vision.ComposeOp(transforms)
  177. data2 = data2.map(input_columns=["image"], operations=transform())
  178. images_list_c = []
  179. images_list_py = []
  180. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  181. image_c = item1["image"]
  182. image_py = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  183. images_list_c.append(image_c)
  184. images_list_py.append(image_py)
  185. # Check if the output images are the same
  186. mse = diff_mse(image_c, image_py)
  187. assert mse < 0.001
  188. if plot:
  189. visualize(images_list_c, images_list_py)
  190. if __name__ == "__main__":
  191. test_random_vertical_op()
  192. test_random_vertical_valid_prob_c()
  193. test_random_vertical_valid_prob_py()
  194. test_random_vertical_invalid_prob_c()
  195. test_random_vertical_invalid_prob_py()
  196. test_random_vertical_comp(True)