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