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_rotation.py 9.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 RandomRotation op in DE
  17. """
  18. import numpy as np
  19. import cv2
  20. import mindspore.dataset as ds
  21. import mindspore.dataset.transforms.py_transforms
  22. import mindspore.dataset.vision.c_transforms as c_vision
  23. import mindspore.dataset.vision.py_transforms as py_vision
  24. from mindspore.dataset.vision.utils import Inter
  25. from mindspore import log as logger
  26. from util import visualize_image, visualize_list, diff_mse, save_and_check_md5, \
  27. config_get_set_seed, config_get_set_num_parallel_workers
  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. GENERATE_GOLDEN = False
  31. def test_random_rotation_op_c(plot=False):
  32. """
  33. Test RandomRotation in c++ transformations op
  34. """
  35. logger.info("test_random_rotation_op_c")
  36. # First dataset
  37. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, shuffle=False)
  38. decode_op = c_vision.Decode()
  39. # use [90, 90] to force rotate 90 degrees, expand is set to be True to match output size
  40. random_rotation_op = c_vision.RandomRotation((90, 90), expand=True)
  41. data1 = data1.map(operations=decode_op, input_columns=["image"])
  42. data1 = data1.map(operations=random_rotation_op, input_columns=["image"])
  43. # Second dataset
  44. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  45. data2 = data2.map(operations=decode_op, input_columns=["image"])
  46. num_iter = 0
  47. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  48. if num_iter > 0:
  49. break
  50. rotation_de = item1["image"]
  51. original = item2["image"]
  52. logger.info("shape before rotate: {}".format(original.shape))
  53. rotation_cv = cv2.rotate(original, cv2.ROTATE_90_COUNTERCLOCKWISE)
  54. mse = diff_mse(rotation_de, rotation_cv)
  55. logger.info("random_rotation_op_{}, mse: {}".format(num_iter + 1, mse))
  56. assert mse == 0
  57. num_iter += 1
  58. if plot:
  59. visualize_image(original, rotation_de, mse, rotation_cv)
  60. def test_random_rotation_op_py(plot=False):
  61. """
  62. Test RandomRotation in python transformations op
  63. """
  64. logger.info("test_random_rotation_op_py")
  65. # First dataset
  66. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, shuffle=False)
  67. # use [90, 90] to force rotate 90 degrees, expand is set to be True to match output size
  68. transform1 = mindspore.dataset.transforms.py_transforms.Compose([py_vision.Decode(),
  69. py_vision.RandomRotation((90, 90), expand=True),
  70. py_vision.ToTensor()])
  71. data1 = data1.map(operations=transform1, input_columns=["image"])
  72. # Second dataset
  73. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  74. transform2 = mindspore.dataset.transforms.py_transforms.Compose([py_vision.Decode(),
  75. py_vision.ToTensor()])
  76. data2 = data2.map(operations=transform2, input_columns=["image"])
  77. num_iter = 0
  78. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  79. if num_iter > 0:
  80. break
  81. rotation_de = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  82. original = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  83. logger.info("shape before rotate: {}".format(original.shape))
  84. rotation_cv = cv2.rotate(original, cv2.ROTATE_90_COUNTERCLOCKWISE)
  85. mse = diff_mse(rotation_de, rotation_cv)
  86. logger.info("random_rotation_op_{}, mse: {}".format(num_iter + 1, mse))
  87. assert mse == 0
  88. num_iter += 1
  89. if plot:
  90. visualize_image(original, rotation_de, mse, rotation_cv)
  91. def test_random_rotation_expand():
  92. """
  93. Test RandomRotation op
  94. """
  95. logger.info("test_random_rotation_op")
  96. # First dataset
  97. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  98. decode_op = c_vision.Decode()
  99. # expand is set to be True to match output size
  100. random_rotation_op = c_vision.RandomRotation((0, 90), expand=True)
  101. data1 = data1.map(operations=decode_op, input_columns=["image"])
  102. data1 = data1.map(operations=random_rotation_op, input_columns=["image"])
  103. num_iter = 0
  104. for item in data1.create_dict_iterator(num_epochs=1):
  105. rotation = item["image"]
  106. logger.info("shape after rotate: {}".format(rotation.shape))
  107. num_iter += 1
  108. def test_random_rotation_md5():
  109. """
  110. Test RandomRotation with md5 check
  111. """
  112. logger.info("Test RandomRotation with md5 check")
  113. original_seed = config_get_set_seed(5)
  114. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  115. # Fisrt dataset
  116. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  117. decode_op = c_vision.Decode()
  118. resize_op = c_vision.RandomRotation((0, 90),
  119. expand=True,
  120. resample=Inter.BILINEAR,
  121. center=(50, 50),
  122. fill_value=150)
  123. data1 = data1.map(operations=decode_op, input_columns=["image"])
  124. data1 = data1.map(operations=resize_op, input_columns=["image"])
  125. # Second dataset
  126. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, shuffle=False)
  127. transform2 = mindspore.dataset.transforms.py_transforms.Compose([py_vision.Decode(),
  128. py_vision.RandomRotation((0, 90),
  129. expand=True,
  130. resample=Inter.BILINEAR,
  131. center=(50, 50),
  132. fill_value=150),
  133. py_vision.ToTensor()])
  134. data2 = data2.map(operations=transform2, input_columns=["image"])
  135. # Compare with expected md5 from images
  136. filename1 = "random_rotation_01_c_result.npz"
  137. save_and_check_md5(data1, filename1, generate_golden=GENERATE_GOLDEN)
  138. filename2 = "random_rotation_01_py_result.npz"
  139. save_and_check_md5(data2, filename2, generate_golden=GENERATE_GOLDEN)
  140. # Restore configuration
  141. ds.config.set_seed(original_seed)
  142. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  143. def test_rotation_diff(plot=False):
  144. """
  145. Test RandomRotation op
  146. """
  147. logger.info("test_random_rotation_op")
  148. # First dataset
  149. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  150. decode_op = c_vision.Decode()
  151. rotation_op = c_vision.RandomRotation((45, 45))
  152. ctrans = [decode_op,
  153. rotation_op
  154. ]
  155. data1 = data1.map(operations=ctrans, input_columns=["image"])
  156. # Second dataset
  157. transforms = [
  158. py_vision.Decode(),
  159. py_vision.RandomRotation((45, 45)),
  160. py_vision.ToTensor(),
  161. ]
  162. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  163. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  164. data2 = data2.map(operations=transform, input_columns=["image"])
  165. num_iter = 0
  166. image_list_c, image_list_py = [], []
  167. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  168. num_iter += 1
  169. c_image = item1["image"]
  170. py_image = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  171. image_list_c.append(c_image)
  172. image_list_py.append(py_image)
  173. logger.info("shape of c_image: {}".format(c_image.shape))
  174. logger.info("shape of py_image: {}".format(py_image.shape))
  175. logger.info("dtype of c_image: {}".format(c_image.dtype))
  176. logger.info("dtype of py_image: {}".format(py_image.dtype))
  177. mse = diff_mse(c_image, py_image)
  178. assert mse < 0.001 # Rounding error
  179. if plot:
  180. visualize_list(image_list_c, image_list_py, visualize_mode=2)
  181. if __name__ == "__main__":
  182. test_random_rotation_op_c(plot=True)
  183. test_random_rotation_op_py(plot=True)
  184. test_random_rotation_expand()
  185. test_random_rotation_md5()
  186. test_rotation_diff(plot=True)