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_auto_augment.py 8.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # Copyright 2021 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 AutoAugment in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. from mindspore.dataset.vision.c_transforms import Decode, AutoAugment, Resize
  21. from mindspore.dataset.vision.utils import AutoAugmentPolicy, Inter
  22. from mindspore import log as logger
  23. from util import visualize_image, visualize_list, diff_mse
  24. image_file = "../data/dataset/testImageNetData/train/class1/1_1.jpg"
  25. data_dir = "../data/dataset/testImageNetData/train/"
  26. def test_auto_augment_pipeline(plot=False):
  27. """
  28. Feature: AutoAugment
  29. Description: test AutoAugment pipeline
  30. Expectation: pass without error
  31. """
  32. logger.info("Test AutoAugment pipeline")
  33. # Original Images
  34. data_set = ds.ImageFolderDataset(dataset_dir=data_dir, shuffle=False)
  35. transforms_original = [Decode(), Resize(size=[224, 224])]
  36. ds_original = data_set.map(operations=transforms_original, input_columns="image")
  37. ds_original = ds_original.batch(512)
  38. for idx, (image, _) in enumerate(ds_original):
  39. if idx == 0:
  40. images_original = image.asnumpy()
  41. else:
  42. images_original = np.append(images_original,
  43. image.asnumpy(),
  44. axis=0)
  45. # Auto Augmented Images with ImageNet policy
  46. data_set1 = ds.ImageFolderDataset(dataset_dir=data_dir, shuffle=False)
  47. auto_augment_op = AutoAugment(AutoAugmentPolicy.IMAGENET, Inter.BICUBIC, 20)
  48. transforms = [Decode(), Resize(size=[224, 224]), auto_augment_op]
  49. ds_auto_augment = data_set1.map(operations=transforms, input_columns="image")
  50. ds_auto_augment = ds_auto_augment.batch(512)
  51. for idx, (image, _) in enumerate(ds_auto_augment):
  52. if idx == 0:
  53. images_auto_augment = image.asnumpy()
  54. else:
  55. images_auto_augment = np.append(images_auto_augment,
  56. image.asnumpy(),
  57. axis=0)
  58. assert images_original.shape[0] == images_auto_augment.shape[0]
  59. if plot:
  60. visualize_list(images_original, images_auto_augment)
  61. num_samples = images_original.shape[0]
  62. mse = np.zeros(num_samples)
  63. for i in range(num_samples):
  64. mse[i] = diff_mse(images_auto_augment[i], images_original[i])
  65. logger.info("MSE= {}".format(str(np.mean(mse))))
  66. # Auto Augmented Images with Cifar10 policy
  67. data_set2 = ds.ImageFolderDataset(dataset_dir=data_dir, shuffle=False)
  68. auto_augment_op = AutoAugment(AutoAugmentPolicy.CIFAR10, Inter.BILINEAR, 20)
  69. transforms = [Decode(), Resize(size=[224, 224]), auto_augment_op]
  70. ds_auto_augment = data_set2.map(operations=transforms, input_columns="image")
  71. ds_auto_augment = ds_auto_augment.batch(512)
  72. for idx, (image, _) in enumerate(ds_auto_augment):
  73. if idx == 0:
  74. images_auto_augment = image.asnumpy()
  75. else:
  76. images_auto_augment = np.append(images_auto_augment,
  77. image.asnumpy(),
  78. axis=0)
  79. assert images_original.shape[0] == images_auto_augment.shape[0]
  80. if plot:
  81. visualize_list(images_original, images_auto_augment)
  82. mse = np.zeros(num_samples)
  83. for i in range(num_samples):
  84. mse[i] = diff_mse(images_auto_augment[i], images_original[i])
  85. logger.info("MSE= {}".format(str(np.mean(mse))))
  86. # Auto Augmented Images with SVHN policy
  87. data_set3 = ds.ImageFolderDataset(dataset_dir=data_dir, shuffle=False)
  88. auto_augment_op = AutoAugment(AutoAugmentPolicy.SVHN, Inter.NEAREST, 20)
  89. transforms = [Decode(), Resize(size=[224, 224]), auto_augment_op]
  90. ds_auto_augment = data_set3.map(operations=transforms, input_columns="image")
  91. ds_auto_augment = ds_auto_augment.batch(512)
  92. for idx, (image, _) in enumerate(ds_auto_augment):
  93. if idx == 0:
  94. images_auto_augment = image.asnumpy()
  95. else:
  96. images_auto_augment = np.append(images_auto_augment,
  97. image.asnumpy(),
  98. axis=0)
  99. assert images_original.shape[0] == images_auto_augment.shape[0]
  100. if plot:
  101. visualize_list(images_original, images_auto_augment)
  102. mse = np.zeros(num_samples)
  103. for i in range(num_samples):
  104. mse[i] = diff_mse(images_auto_augment[i], images_original[i])
  105. logger.info("MSE= {}".format(str(np.mean(mse))))
  106. def test_auto_augment_eager(plot=False):
  107. """
  108. Feature: AutoAugment
  109. Description: test AutoAugment eager
  110. Expectation: pass without error
  111. """
  112. img = np.fromfile(image_file, dtype=np.uint8)
  113. logger.info("Image.type: {}, Image.shape: {}".format(type(img), img.shape))
  114. img = Decode()(img)
  115. img_auto_augmented = AutoAugment()(img)
  116. if plot:
  117. visualize_image(img, img_auto_augmented)
  118. logger.info("Image.type: {}, Image.shape: {}".format(type(img_auto_augmented), img_auto_augmented.shape))
  119. mse = diff_mse(img_auto_augmented, img)
  120. logger.info("MSE= {}".format(str(mse)))
  121. def test_auto_augment_invalid_policy():
  122. """
  123. Feature: AutoAugment
  124. Description: test AutoAugment with invalid policy
  125. Expectation: throw TypeError
  126. """
  127. logger.info("test_auto_augment_invalid_policy")
  128. dataset = ds.ImageFolderDataset(data_dir, 1, shuffle=False, decode=True)
  129. try:
  130. auto_augment_op = AutoAugment(policy="invalid")
  131. dataset.map(operations=auto_augment_op, input_columns=['image'])
  132. except TypeError as e:
  133. logger.info("Got an exception in DE: {}".format(str(e)))
  134. assert "Argument policy with value invalid is not of type [<enum 'AutoAugmentPolicy'>]" in str(e)
  135. def test_auto_augment_invalid_interpolation():
  136. """
  137. Feature: AutoAugment
  138. Description: test AutoAugment with invalid interpolation
  139. Expectation: throw TypeError
  140. """
  141. logger.info("test_auto_augment_invalid_interpolation")
  142. dataset = ds.ImageFolderDataset(data_dir, 1, shuffle=False, decode=True)
  143. try:
  144. auto_augment_op = AutoAugment(interpolation="invalid")
  145. dataset.map(operations=auto_augment_op, input_columns=['image'])
  146. except TypeError as e:
  147. logger.info("Got an exception in DE: {}".format(str(e)))
  148. assert "Argument interpolation with value invalid is not of type [<enum 'Inter'>]" in str(e)
  149. def test_auto_augment_invalid_fill_value():
  150. """
  151. Feature: AutoAugment
  152. Description: test AutoAugment with invalid fill_value
  153. Expectation: throw TypeError or ValueError
  154. """
  155. logger.info("test_auto_augment_invalid_fill_value")
  156. dataset = ds.ImageFolderDataset(data_dir, 1, shuffle=False, decode=True)
  157. try:
  158. auto_augment_op = AutoAugment(fill_value=(10, 10))
  159. dataset.map(operations=auto_augment_op, input_columns=['image'])
  160. except TypeError as e:
  161. logger.info("Got an exception in DE: {}".format(str(e)))
  162. assert "fill_value should be a single integer or a 3-tuple." in str(e)
  163. try:
  164. auto_augment_op = AutoAugment(fill_value=300)
  165. dataset.map(operations=auto_augment_op, input_columns=['image'])
  166. except ValueError as e:
  167. logger.info("Got an exception in DE: {}".format(str(e)))
  168. assert "is not within the required interval of [0, 255]." in str(e)
  169. if __name__ == "__main__":
  170. test_auto_augment_pipeline(plot=True)
  171. test_auto_augment_eager(plot=True)
  172. test_auto_augment_invalid_policy()
  173. test_auto_augment_invalid_interpolation()
  174. test_auto_augment_invalid_fill_value()