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_lighting.py 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 RandomLighting op 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.py_transforms as F
  23. import mindspore.dataset.vision.c_transforms as C
  24. from mindspore import log as logger
  25. from util import visualize_list, diff_mse, save_and_check_md5, \
  26. config_get_set_seed, config_get_set_num_parallel_workers
  27. DATA_DIR = "../data/dataset/testImageNetData/train/"
  28. MNIST_DATA_DIR = "../data/dataset/testMnistData"
  29. GENERATE_GOLDEN = False
  30. def test_random_lighting_py(alpha=1, plot=False):
  31. """
  32. Feature: RandomLighting
  33. Description: test RandomLighting python op
  34. Expectation: equal results
  35. """
  36. logger.info("Test RandomLighting python op")
  37. # Original Images
  38. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  39. transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
  40. F.Resize((224, 224)),
  41. F.ToTensor()])
  42. ds_original = data.map(operations=transforms_original, input_columns="image")
  43. ds_original = ds_original.batch(512)
  44. for idx, (image, _) in enumerate(ds_original.create_tuple_iterator(num_epochs=1, output_numpy=True)):
  45. if idx == 0:
  46. images_original = np.transpose(image, (0, 2, 3, 1))
  47. else:
  48. images_original = np.append(images_original, np.transpose(image, (0, 2, 3, 1)), axis=0)
  49. # Random Lighting Adjusted Images
  50. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  51. alpha = alpha if alpha is not None else 0.05
  52. py_op = F.RandomLighting(alpha)
  53. transforms_random_lighting = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
  54. F.Resize((224, 224)),
  55. py_op,
  56. F.ToTensor()])
  57. ds_random_lighting = data.map(operations=transforms_random_lighting, input_columns="image")
  58. ds_random_lighting = ds_random_lighting.batch(512)
  59. for idx, (image, _) in enumerate(ds_random_lighting.create_tuple_iterator(num_epochs=1, output_numpy=True)):
  60. if idx == 0:
  61. images_random_lighting = np.transpose(image, (0, 2, 3, 1))
  62. else:
  63. images_random_lighting = np.append(images_random_lighting, np.transpose(image, (0, 2, 3, 1)), axis=0)
  64. num_samples = images_original.shape[0]
  65. mse = np.zeros(num_samples)
  66. for i in range(num_samples):
  67. mse[i] = diff_mse(images_random_lighting[i], images_original[i])
  68. logger.info("MSE= {}".format(str(np.mean(mse))))
  69. if plot:
  70. visualize_list(images_original, images_random_lighting)
  71. def test_random_lighting_py_md5():
  72. """
  73. Feature: RandomLighting
  74. Description: test RandomLighting python op with md5 comparison
  75. Expectation: same MD5
  76. """
  77. logger.info("Test RandomLighting python op with md5 comparison")
  78. original_seed = config_get_set_seed(140)
  79. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  80. # define map operations
  81. transforms = [
  82. F.Decode(),
  83. F.Resize((224, 224)),
  84. F.RandomLighting(1),
  85. F.ToTensor()
  86. ]
  87. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  88. # Generate dataset
  89. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  90. data = data.map(operations=transform, input_columns=["image"])
  91. # check results with md5 comparison
  92. filename = "random_lighting_py_01_result.npz"
  93. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  94. # Restore configuration
  95. ds.config.set_seed(original_seed)
  96. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  97. def test_random_lighting_c(alpha=1, plot=False):
  98. """
  99. Feature: RandomLighting
  100. Description: test RandomLighting cpp op
  101. Expectation: equal results from Mindspore and benchmark
  102. """
  103. logger.info("Test RandomLighting cpp op")
  104. # Original Images
  105. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  106. transforms_original = [C.Decode(), C.Resize((224, 224))]
  107. ds_original = data.map(operations=transforms_original, input_columns="image")
  108. ds_original = ds_original.batch(512)
  109. for idx, (image, _) in enumerate(ds_original.create_tuple_iterator(num_epochs=1, output_numpy=True)):
  110. if idx == 0:
  111. images_original = image
  112. else:
  113. images_original = np.append(images_original, image, axis=0)
  114. # Random Lighting Adjusted Images
  115. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  116. alpha = alpha if alpha is not None else 0.05
  117. c_op = C.RandomLighting(alpha)
  118. transforms_random_lighting = [C.Decode(), C.Resize((224, 224)), c_op]
  119. ds_random_lighting = data.map(operations=transforms_random_lighting, input_columns="image")
  120. ds_random_lighting = ds_random_lighting.batch(512)
  121. for idx, (image, _) in enumerate(ds_random_lighting.create_tuple_iterator(num_epochs=1, output_numpy=True)):
  122. if idx == 0:
  123. images_random_lighting = image
  124. else:
  125. images_random_lighting = np.append(images_random_lighting, image, axis=0)
  126. num_samples = images_original.shape[0]
  127. mse = np.zeros(num_samples)
  128. for i in range(num_samples):
  129. mse[i] = diff_mse(images_random_lighting[i], images_original[i])
  130. logger.info("MSE= {}".format(str(np.mean(mse))))
  131. if plot:
  132. visualize_list(images_original, images_random_lighting)
  133. def test_random_lighting_c_py(alpha=1, plot=False):
  134. """
  135. Feature: RandomLighting
  136. Description: test Random Lighting Cpp and Python Op
  137. Expectation: equal results from Cpp and Python
  138. """
  139. logger.info("Test RandomLighting Cpp and python Op")
  140. # RandomLighting Images
  141. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  142. data = data.map(operations=[C.Decode(), C.Resize((200, 300))], input_columns=["image"])
  143. python_op = F.RandomLighting(alpha)
  144. c_op = C.RandomLighting(alpha)
  145. transforms_op = mindspore.dataset.transforms.py_transforms.Compose([lambda img: F.ToPIL()(img.astype(np.uint8)),
  146. python_op,
  147. np.array])
  148. ds_random_lighting_py = data.map(operations=transforms_op, input_columns="image")
  149. ds_random_lighting_py = ds_random_lighting_py.batch(512)
  150. for idx, (image, _) in enumerate(ds_random_lighting_py.create_tuple_iterator(num_epochs=1, output_numpy=True)):
  151. if idx == 0:
  152. images_random_lighting_py = image
  153. else:
  154. images_random_lighting_py = np.append(images_random_lighting_py, image, axis=0)
  155. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  156. data = data.map(operations=[C.Decode(), C.Resize((200, 300))], input_columns=["image"])
  157. ds_images_random_lighting_c = data.map(operations=c_op, input_columns="image")
  158. ds_random_lighting_c = ds_images_random_lighting_c.batch(512)
  159. for idx, (image, _) in enumerate(ds_random_lighting_c.create_tuple_iterator(num_epochs=1, output_numpy=True)):
  160. if idx == 0:
  161. images_random_lighting_c = image
  162. else:
  163. images_random_lighting_c = np.append(images_random_lighting_c, image, axis=0)
  164. num_samples = images_random_lighting_c.shape[0]
  165. mse = np.zeros(num_samples)
  166. for i in range(num_samples):
  167. mse[i] = diff_mse(images_random_lighting_c[i], images_random_lighting_py[i])
  168. logger.info("MSE= {}".format(str(np.mean(mse))))
  169. if plot:
  170. visualize_list(images_random_lighting_c, images_random_lighting_py, visualize_mode=2)
  171. def test_random_lighting_invalid_params():
  172. """
  173. Feature: RandomLighting
  174. Description: test RandomLighting with invalid input parameters
  175. Expectation: throw ValueError or TypeError
  176. """
  177. logger.info("Test RandomLighting with invalid input parameters.")
  178. with pytest.raises(ValueError) as error_info:
  179. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  180. data = data.map(operations=[C.Decode(), C.Resize((224, 224)),
  181. C.RandomLighting(-2)], input_columns=["image"])
  182. assert "Input alpha is not within the required interval of [0, 16777216]." in str(error_info.value)
  183. with pytest.raises(TypeError) as error_info:
  184. data = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  185. data = data.map(operations=[C.Decode(), C.Resize((224, 224)),
  186. C.RandomLighting('1')], input_columns=["image"])
  187. err_msg = "Argument alpha with value 1 is not of type [<class 'float'>, <class 'int'>], but got <class 'str'>."
  188. assert err_msg in str(error_info.value)
  189. if __name__ == "__main__":
  190. test_random_lighting_py()
  191. test_random_lighting_py_md5()
  192. test_random_lighting_c()
  193. test_random_lighting_c_py()
  194. test_random_lighting_invalid_params()