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