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

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