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_normalizeOp.py 12 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 Normalize op in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.transforms.py_transforms
  21. import mindspore.dataset.vision.c_transforms as c_vision
  22. import mindspore.dataset.vision.py_transforms as py_vision
  23. from mindspore import log as logger
  24. from util import diff_mse, save_and_check_md5, visualize_image
  25. DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  26. SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
  27. GENERATE_GOLDEN = False
  28. def normalize_np(image, mean, std):
  29. """
  30. Apply the normalization
  31. """
  32. # DE decodes the image in RGB by deafult, hence
  33. # the values here are in RGB
  34. image = np.array(image, np.float32)
  35. image = image - np.array(mean)
  36. image = image * (1.0 / np.array(std))
  37. return image
  38. def util_test_normalize(mean, std, op_type):
  39. """
  40. Utility function for testing Normalize. Input arguments are given by other tests
  41. """
  42. if op_type == "cpp":
  43. # define map operations
  44. decode_op = c_vision.Decode()
  45. normalize_op = c_vision.Normalize(mean, std)
  46. # Generate dataset
  47. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  48. data = data.map(operations=decode_op, input_columns=["image"])
  49. data = data.map(operations=normalize_op, input_columns=["image"])
  50. elif op_type == "python":
  51. # define map operations
  52. transforms = [
  53. py_vision.Decode(),
  54. py_vision.ToTensor(),
  55. py_vision.Normalize(mean, std)
  56. ]
  57. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  58. # Generate dataset
  59. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  60. data = data.map(operations=transform, input_columns=["image"])
  61. else:
  62. raise ValueError("Wrong parameter value")
  63. return data
  64. def util_test_normalize_grayscale(num_output_channels, mean, std):
  65. """
  66. Utility function for testing Normalize. Input arguments are given by other tests
  67. """
  68. transforms = [
  69. py_vision.Decode(),
  70. py_vision.Grayscale(num_output_channels),
  71. py_vision.ToTensor(),
  72. py_vision.Normalize(mean, std)
  73. ]
  74. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  75. # Generate dataset
  76. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  77. data = data.map(operations=transform, input_columns=["image"])
  78. return data
  79. def test_normalize_op_c(plot=False):
  80. """
  81. Test Normalize in cpp transformations
  82. """
  83. logger.info("Test Normalize in cpp")
  84. mean = [121.0, 115.0, 100.0]
  85. std = [70.0, 68.0, 71.0]
  86. # define map operations
  87. decode_op = c_vision.Decode()
  88. normalize_op = c_vision.Normalize(mean, std)
  89. # First dataset
  90. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  91. data1 = data1.map(operations=decode_op, input_columns=["image"])
  92. data1 = data1.map(operations=normalize_op, input_columns=["image"])
  93. # Second dataset
  94. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  95. data2 = data2.map(operations=decode_op, input_columns=["image"])
  96. num_iter = 0
  97. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  98. image_de_normalized = item1["image"]
  99. image_original = item2["image"]
  100. image_np_normalized = normalize_np(image_original, mean, std)
  101. mse = diff_mse(image_de_normalized, image_np_normalized)
  102. logger.info("image_{}, mse: {}".format(num_iter + 1, mse))
  103. assert mse < 0.01
  104. if plot:
  105. visualize_image(image_original, image_de_normalized, mse, image_np_normalized)
  106. num_iter += 1
  107. def test_normalize_op_py(plot=False):
  108. """
  109. Test Normalize in python transformations
  110. """
  111. logger.info("Test Normalize in python")
  112. mean = [0.475, 0.45, 0.392]
  113. std = [0.275, 0.267, 0.278]
  114. # define map operations
  115. transforms = [
  116. py_vision.Decode(),
  117. py_vision.ToTensor()
  118. ]
  119. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  120. normalize_op = py_vision.Normalize(mean, std)
  121. # First dataset
  122. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  123. data1 = data1.map(operations=transform, input_columns=["image"])
  124. data1 = data1.map(operations=normalize_op, input_columns=["image"])
  125. # Second dataset
  126. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  127. data2 = data2.map(operations=transform, input_columns=["image"])
  128. num_iter = 0
  129. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  130. image_de_normalized = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  131. image_np_normalized = (normalize_np(item2["image"].transpose(1, 2, 0), mean, std) * 255).astype(np.uint8)
  132. image_original = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  133. mse = diff_mse(image_de_normalized, image_np_normalized)
  134. logger.info("image_{}, mse: {}".format(num_iter + 1, mse))
  135. assert mse < 0.01
  136. if plot:
  137. visualize_image(image_original, image_de_normalized, mse, image_np_normalized)
  138. num_iter += 1
  139. def test_decode_op():
  140. """
  141. Test Decode op
  142. """
  143. logger.info("Test Decode")
  144. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image", "label"], num_parallel_workers=1,
  145. shuffle=False)
  146. # define map operations
  147. decode_op = c_vision.Decode()
  148. # apply map operations on images
  149. data1 = data1.map(operations=decode_op, input_columns=["image"])
  150. num_iter = 0
  151. for item in data1.create_dict_iterator(num_epochs=1):
  152. logger.info("Looping inside iterator {}".format(num_iter))
  153. _ = item["image"]
  154. num_iter += 1
  155. def test_decode_normalize_op():
  156. """
  157. Test Decode op followed by Normalize op
  158. """
  159. logger.info("Test [Decode, Normalize] in one Map")
  160. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image", "label"], num_parallel_workers=1,
  161. shuffle=False)
  162. # define map operations
  163. decode_op = c_vision.Decode()
  164. normalize_op = c_vision.Normalize([121.0, 115.0, 100.0], [70.0, 68.0, 71.0])
  165. # apply map operations on images
  166. data1 = data1.map(operations=[decode_op, normalize_op], input_columns=["image"])
  167. num_iter = 0
  168. for item in data1.create_dict_iterator(num_epochs=1):
  169. logger.info("Looping inside iterator {}".format(num_iter))
  170. _ = item["image"]
  171. num_iter += 1
  172. def test_normalize_md5_01():
  173. """
  174. Test Normalize with md5 check: valid mean and std
  175. expected to pass
  176. """
  177. logger.info("test_normalize_md5_01")
  178. data_c = util_test_normalize([121.0, 115.0, 100.0], [70.0, 68.0, 71.0], "cpp")
  179. data_py = util_test_normalize([0.475, 0.45, 0.392], [0.275, 0.267, 0.278], "python")
  180. # check results with md5 comparison
  181. filename1 = "normalize_01_c_result.npz"
  182. filename2 = "normalize_01_py_result.npz"
  183. save_and_check_md5(data_c, filename1, generate_golden=GENERATE_GOLDEN)
  184. save_and_check_md5(data_py, filename2, generate_golden=GENERATE_GOLDEN)
  185. def test_normalize_md5_02():
  186. """
  187. Test Normalize with md5 check: len(mean)=len(std)=1 with RGB images
  188. expected to pass
  189. """
  190. logger.info("test_normalize_md5_02")
  191. data_py = util_test_normalize([0.475], [0.275], "python")
  192. # check results with md5 comparison
  193. filename2 = "normalize_02_py_result.npz"
  194. save_and_check_md5(data_py, filename2, generate_golden=GENERATE_GOLDEN)
  195. def test_normalize_exception_unequal_size_c():
  196. """
  197. Test Normalize in c transformation: len(mean) != len(std)
  198. expected to raise ValueError
  199. """
  200. logger.info("test_normalize_exception_unequal_size_c")
  201. try:
  202. _ = c_vision.Normalize([100, 250, 125], [50, 50, 75, 75])
  203. except ValueError as e:
  204. logger.info("Got an exception in DE: {}".format(str(e)))
  205. assert str(e) == "Length of mean and std must be equal"
  206. def test_normalize_exception_unequal_size_py():
  207. """
  208. Test Normalize in python transformation: len(mean) != len(std)
  209. expected to raise ValueError
  210. """
  211. logger.info("test_normalize_exception_unequal_size_py")
  212. try:
  213. _ = py_vision.Normalize([0.50, 0.30, 0.75], [0.18, 0.32, 0.71, 0.72])
  214. except ValueError as e:
  215. logger.info("Got an exception in DE: {}".format(str(e)))
  216. assert str(e) == "Length of mean and std must be equal"
  217. def test_normalize_exception_invalid_size_py():
  218. """
  219. Test Normalize in python transformation: len(mean)=len(std)=2
  220. expected to raise RuntimeError
  221. """
  222. logger.info("test_normalize_exception_invalid_size_py")
  223. data = util_test_normalize([0.75, 0.25], [0.18, 0.32], "python")
  224. try:
  225. _ = data.create_dict_iterator(num_epochs=1).get_next()
  226. except RuntimeError as e:
  227. logger.info("Got an exception in DE: {}".format(str(e)))
  228. assert "Length of mean and std must both be 1 or" in str(e)
  229. def test_normalize_exception_invalid_range_py():
  230. """
  231. Test Normalize in python transformation: value is not in range [0,1]
  232. expected to raise ValueError
  233. """
  234. logger.info("test_normalize_exception_invalid_range_py")
  235. try:
  236. _ = py_vision.Normalize([0.75, 1.25, 0.5], [0.1, 0.18, 1.32])
  237. except ValueError as e:
  238. logger.info("Got an exception in DE: {}".format(str(e)))
  239. assert "Input mean_value is not within the required interval of (0.0 to 1.0)." in str(e)
  240. def test_normalize_grayscale_md5_01():
  241. """
  242. Test Normalize with md5 check: len(mean)=len(std)=1 with 1 channel grayscale images
  243. expected to pass
  244. """
  245. logger.info("test_normalize_grayscale_md5_01")
  246. data = util_test_normalize_grayscale(1, [0.5], [0.175])
  247. # check results with md5 comparison
  248. filename = "normalize_03_py_result.npz"
  249. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  250. def test_normalize_grayscale_md5_02():
  251. """
  252. Test Normalize with md5 check: len(mean)=len(std)=3 with 3 channel grayscale images
  253. expected to pass
  254. """
  255. logger.info("test_normalize_grayscale_md5_02")
  256. data = util_test_normalize_grayscale(3, [0.5, 0.5, 0.5], [0.175, 0.235, 0.512])
  257. # check results with md5 comparison
  258. filename = "normalize_04_py_result.npz"
  259. save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
  260. def test_normalize_grayscale_exception():
  261. """
  262. Test Normalize: len(mean)=len(std)=3 with 1 channel grayscale images
  263. expected to raise RuntimeError
  264. """
  265. logger.info("test_normalize_grayscale_exception")
  266. try:
  267. _ = util_test_normalize_grayscale(1, [0.5, 0.5, 0.5], [0.175, 0.235, 0.512])
  268. except RuntimeError as e:
  269. logger.info("Got an exception in DE: {}".format(str(e)))
  270. assert "Input is not within the required range" in str(e)
  271. if __name__ == "__main__":
  272. test_decode_op()
  273. test_decode_normalize_op()
  274. test_normalize_op_c(plot=True)
  275. test_normalize_op_py(plot=True)
  276. test_normalize_md5_01()
  277. test_normalize_md5_02()
  278. test_normalize_exception_unequal_size_c()
  279. test_normalize_exception_unequal_size_py()
  280. test_normalize_exception_invalid_size_py()
  281. test_normalize_exception_invalid_range_py()
  282. test_normalize_grayscale_md5_01()
  283. test_normalize_grayscale_md5_02()
  284. test_normalize_grayscale_exception()