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 13 kB

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