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_uniform_augment.py 11 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # Copyright 2020-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 UniformAugment in DE
  17. """
  18. import numpy as np
  19. import pytest
  20. import mindspore.dataset as ds
  21. import mindspore.dataset.transforms.py_transforms
  22. import mindspore.dataset.vision.c_transforms as C
  23. import mindspore.dataset.vision.py_transforms as F
  24. from mindspore import log as logger
  25. from util import visualize_list, diff_mse
  26. DATA_DIR = "../data/dataset/testImageNetData/train/"
  27. def test_uniform_augment_callable(num_ops=2):
  28. """
  29. Test UniformAugment is callable
  30. """
  31. logger.info("test_uniform_augment_callable")
  32. img = np.fromfile("../data/dataset/apple.jpg", dtype=np.uint8)
  33. logger.info("Image.type: {}, Image.shape: {}".format(type(img), img.shape))
  34. decode_op = C.Decode()
  35. img = decode_op(img)
  36. assert img.shape == (2268, 4032, 3)
  37. transforms_ua = [C.RandomCrop(size=[400, 400], padding=[32, 32, 32, 32]),
  38. C.RandomCrop(size=[400, 400], padding=[32, 32, 32, 32])]
  39. uni_aug = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  40. img = uni_aug(img)
  41. assert img.shape == (2268, 4032, 3) or img.shape == (400, 400, 3)
  42. def test_uniform_augment(plot=False, num_ops=2):
  43. """
  44. Test UniformAugment
  45. """
  46. logger.info("Test UniformAugment")
  47. # Original Images
  48. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  49. transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
  50. F.Resize((224, 224)),
  51. F.ToTensor()])
  52. ds_original = data_set.map(operations=transforms_original, input_columns="image")
  53. ds_original = ds_original.batch(512)
  54. for idx, (image, _) in enumerate(ds_original):
  55. if idx == 0:
  56. images_original = np.transpose(image.asnumpy(), (0, 2, 3, 1))
  57. else:
  58. images_original = np.append(images_original,
  59. np.transpose(image.asnumpy(), (0, 2, 3, 1)),
  60. axis=0)
  61. # UniformAugment Images
  62. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  63. transform_list = [F.RandomRotation(45),
  64. F.RandomColor(),
  65. F.RandomSharpness(),
  66. F.Invert(),
  67. F.AutoContrast(),
  68. F.Equalize()]
  69. transforms_ua = \
  70. mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
  71. F.Resize((224, 224)),
  72. F.UniformAugment(transforms=transform_list,
  73. num_ops=num_ops),
  74. F.ToTensor()])
  75. ds_ua = data_set.map(operations=transforms_ua, input_columns="image")
  76. ds_ua = ds_ua.batch(512)
  77. for idx, (image, _) in enumerate(ds_ua):
  78. if idx == 0:
  79. images_ua = np.transpose(image.asnumpy(), (0, 2, 3, 1))
  80. else:
  81. images_ua = np.append(images_ua,
  82. np.transpose(image.asnumpy(), (0, 2, 3, 1)),
  83. axis=0)
  84. num_samples = images_original.shape[0]
  85. mse = np.zeros(num_samples)
  86. for i in range(num_samples):
  87. mse[i] = diff_mse(images_ua[i], images_original[i])
  88. logger.info("MSE= {}".format(str(np.mean(mse))))
  89. if plot:
  90. visualize_list(images_original, images_ua)
  91. def test_cpp_uniform_augment(plot=False, num_ops=2):
  92. """
  93. Test UniformAugment
  94. """
  95. logger.info("Test CPP UniformAugment")
  96. # Original Images
  97. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  98. transforms_original = [C.Decode(), C.Resize(size=[224, 224]),
  99. F.ToTensor()]
  100. ds_original = data_set.map(operations=transforms_original, input_columns="image")
  101. ds_original = ds_original.batch(512)
  102. for idx, (image, _) in enumerate(ds_original):
  103. if idx == 0:
  104. images_original = np.transpose(image.asnumpy(), (0, 2, 3, 1))
  105. else:
  106. images_original = np.append(images_original,
  107. np.transpose(image.asnumpy(), (0, 2, 3, 1)),
  108. axis=0)
  109. # UniformAugment Images
  110. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  111. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  112. C.RandomHorizontalFlip(),
  113. C.RandomVerticalFlip(),
  114. C.RandomColorAdjust(),
  115. C.RandomRotation(degrees=45)]
  116. uni_aug = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  117. transforms_all = [C.Decode(), C.Resize(size=[224, 224]),
  118. uni_aug,
  119. F.ToTensor()]
  120. ds_ua = data_set.map(operations=transforms_all, input_columns="image", num_parallel_workers=1)
  121. ds_ua = ds_ua.batch(512)
  122. for idx, (image, _) in enumerate(ds_ua):
  123. if idx == 0:
  124. images_ua = np.transpose(image.asnumpy(), (0, 2, 3, 1))
  125. else:
  126. images_ua = np.append(images_ua,
  127. np.transpose(image.asnumpy(), (0, 2, 3, 1)),
  128. axis=0)
  129. if plot:
  130. visualize_list(images_original, images_ua)
  131. num_samples = images_original.shape[0]
  132. mse = np.zeros(num_samples)
  133. for i in range(num_samples):
  134. mse[i] = diff_mse(images_ua[i], images_original[i])
  135. logger.info("MSE= {}".format(str(np.mean(mse))))
  136. def test_cpp_uniform_augment_exception_pyops(num_ops=2):
  137. """
  138. Test UniformAugment invalid op in operations
  139. """
  140. logger.info("Test CPP UniformAugment invalid OP exception")
  141. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  142. C.RandomHorizontalFlip(),
  143. C.RandomVerticalFlip(),
  144. C.RandomColorAdjust(),
  145. C.RandomRotation(degrees=45),
  146. F.Invert()]
  147. with pytest.raises(TypeError) as e:
  148. C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  149. logger.info("Got an exception in DE: {}".format(str(e)))
  150. assert "Type of Transforms[5] must be c_transform" in str(e.value)
  151. def test_cpp_uniform_augment_exception_large_numops(num_ops=6):
  152. """
  153. Test UniformAugment invalid large number of ops
  154. """
  155. logger.info("Test CPP UniformAugment invalid large num_ops exception")
  156. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  157. C.RandomHorizontalFlip(),
  158. C.RandomVerticalFlip(),
  159. C.RandomColorAdjust(),
  160. C.RandomRotation(degrees=45)]
  161. try:
  162. _ = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  163. except Exception as e:
  164. logger.info("Got an exception in DE: {}".format(str(e)))
  165. assert "num_ops" in str(e)
  166. def test_cpp_uniform_augment_exception_nonpositive_numops(num_ops=0):
  167. """
  168. Test UniformAugment invalid non-positive number of ops
  169. """
  170. logger.info("Test CPP UniformAugment invalid non-positive num_ops exception")
  171. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  172. C.RandomHorizontalFlip(),
  173. C.RandomVerticalFlip(),
  174. C.RandomColorAdjust(),
  175. C.RandomRotation(degrees=45)]
  176. try:
  177. _ = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  178. except Exception as e:
  179. logger.info("Got an exception in DE: {}".format(str(e)))
  180. assert "Input num_ops must be greater than 0" in str(e)
  181. def test_cpp_uniform_augment_exception_float_numops(num_ops=2.5):
  182. """
  183. Test UniformAugment invalid float number of ops
  184. """
  185. logger.info("Test CPP UniformAugment invalid float num_ops exception")
  186. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  187. C.RandomHorizontalFlip(),
  188. C.RandomVerticalFlip(),
  189. C.RandomColorAdjust(),
  190. C.RandomRotation(degrees=45)]
  191. try:
  192. _ = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  193. except Exception as e:
  194. logger.info("Got an exception in DE: {}".format(str(e)))
  195. assert "Argument num_ops with value 2.5 is not of type (<class 'int'>,)" in str(e)
  196. def test_cpp_uniform_augment_random_crop_badinput(num_ops=1):
  197. """
  198. Test UniformAugment with greater crop size
  199. """
  200. logger.info("Test CPP UniformAugment with random_crop bad input")
  201. batch_size = 2
  202. cifar10_dir = "../data/dataset/testCifar10Data"
  203. ds1 = ds.Cifar10Dataset(cifar10_dir, shuffle=False) # shape = [32,32,3]
  204. transforms_ua = [
  205. # Note: crop size [224, 224] > image size [32, 32]
  206. C.RandomCrop(size=[224, 224]),
  207. C.RandomHorizontalFlip()
  208. ]
  209. uni_aug = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  210. ds1 = ds1.map(operations=uni_aug, input_columns="image")
  211. # apply DatasetOps
  212. ds1 = ds1.batch(batch_size, drop_remainder=True, num_parallel_workers=1)
  213. num_batches = 0
  214. try:
  215. for _ in ds1.create_dict_iterator(num_epochs=1, output_numpy=True):
  216. num_batches += 1
  217. except Exception as e:
  218. assert "crop size" in str(e)
  219. if __name__ == "__main__":
  220. test_uniform_augment_callable(num_ops=2)
  221. test_uniform_augment(num_ops=1, plot=True)
  222. test_cpp_uniform_augment(num_ops=1, plot=True)
  223. test_cpp_uniform_augment_exception_pyops(num_ops=1)
  224. test_cpp_uniform_augment_exception_large_numops(num_ops=6)
  225. test_cpp_uniform_augment_exception_nonpositive_numops(num_ops=0)
  226. test_cpp_uniform_augment_exception_float_numops(num_ops=2.5)
  227. test_cpp_uniform_augment_random_crop_badinput(num_ops=1)