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_normalizepad_op.py 7.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # Copyright 2020 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, 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 normalizepad_np(image, mean, std):
  29. """
  30. Apply the normalize+pad
  31. """
  32. # DE decodes the image in RGB by default, 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. zeros = np.zeros([image.shape[0], image.shape[1], 1], dtype=np.float32)
  38. output = np.concatenate((image, zeros), axis=2)
  39. return output
  40. def test_normalizepad_op_c(plot=False):
  41. """
  42. Test NormalizePad in cpp transformations
  43. """
  44. logger.info("Test Normalize in cpp")
  45. mean = [121.0, 115.0, 100.0]
  46. std = [70.0, 68.0, 71.0]
  47. # define map operations
  48. decode_op = c_vision.Decode()
  49. normalizepad_op = c_vision.NormalizePad(mean, std)
  50. # First dataset
  51. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  52. data1 = data1.map(operations=decode_op, input_columns=["image"])
  53. data1 = data1.map(operations=normalizepad_op, input_columns=["image"])
  54. # Second dataset
  55. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  56. data2 = data2.map(operations=decode_op, input_columns=["image"])
  57. num_iter = 0
  58. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  59. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  60. image_de_normalized = item1["image"]
  61. image_original = item2["image"]
  62. image_np_normalized = normalizepad_np(image_original, mean, std)
  63. mse = diff_mse(image_de_normalized, image_np_normalized)
  64. logger.info("image_{}, mse: {}".format(num_iter + 1, mse))
  65. assert mse < 0.01
  66. if plot:
  67. visualize_image(image_original, image_de_normalized, mse, image_np_normalized)
  68. num_iter += 1
  69. def test_normalizepad_op_py(plot=False):
  70. """
  71. Test NormalizePad in python transformations
  72. """
  73. logger.info("Test Normalize in python")
  74. mean = [0.475, 0.45, 0.392]
  75. std = [0.275, 0.267, 0.278]
  76. # define map operations
  77. transforms = [
  78. py_vision.Decode(),
  79. py_vision.ToTensor()
  80. ]
  81. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  82. normalizepad_op = py_vision.NormalizePad(mean, std)
  83. # First dataset
  84. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  85. data1 = data1.map(operations=transform, input_columns=["image"])
  86. data1 = data1.map(operations=normalizepad_op, input_columns=["image"])
  87. # Second dataset
  88. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  89. data2 = data2.map(operations=transform, input_columns=["image"])
  90. num_iter = 0
  91. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  92. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  93. image_de_normalized = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  94. image_np_normalized = (normalizepad_np(item2["image"].transpose(1, 2, 0), mean, std) * 255).astype(np.uint8)
  95. image_original = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  96. mse = diff_mse(image_de_normalized, image_np_normalized)
  97. logger.info("image_{}, mse: {}".format(num_iter + 1, mse))
  98. assert mse < 0.01
  99. if plot:
  100. visualize_image(image_original, image_de_normalized, mse, image_np_normalized)
  101. num_iter += 1
  102. def test_decode_normalizepad_op():
  103. """
  104. Test Decode op followed by NormalizePad op
  105. """
  106. logger.info("Test [Decode, Normalize] in one Map")
  107. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image", "label"], num_parallel_workers=1,
  108. shuffle=False)
  109. # define map operations
  110. decode_op = c_vision.Decode()
  111. normalizepad_op = c_vision.NormalizePad([121.0, 115.0, 100.0], [70.0, 68.0, 71.0], "float16")
  112. # apply map operations on images
  113. data1 = data1.map(operations=[decode_op, normalizepad_op], input_columns=["image"])
  114. num_iter = 0
  115. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  116. logger.info("Looping inside iterator {}".format(num_iter))
  117. assert item["image"].dtype == np.float16
  118. num_iter += 1
  119. def test_normalizepad_exception_unequal_size_c():
  120. """
  121. Test NormalizePad in c transformation: len(mean) != len(std)
  122. expected to raise ValueError
  123. """
  124. logger.info("test_normalize_exception_unequal_size_c")
  125. try:
  126. _ = c_vision.NormalizePad([100, 250, 125], [50, 50, 75, 75])
  127. except ValueError as e:
  128. logger.info("Got an exception in DE: {}".format(str(e)))
  129. assert str(e) == "Length of mean and std must be equal."
  130. try:
  131. _ = c_vision.NormalizePad([100, 250, 125], [50, 50, 75], 1)
  132. except TypeError as e:
  133. logger.info("Got an exception in DE: {}".format(str(e)))
  134. assert str(e) == "dtype should be string."
  135. try:
  136. _ = c_vision.NormalizePad([100, 250, 125], [50, 50, 75], "")
  137. except ValueError as e:
  138. logger.info("Got an exception in DE: {}".format(str(e)))
  139. assert str(e) == "dtype only support float32 or float16."
  140. def test_normalizepad_exception_unequal_size_py():
  141. """
  142. Test NormalizePad in python transformation: len(mean) != len(std)
  143. expected to raise ValueError
  144. """
  145. logger.info("test_normalizepad_exception_unequal_size_py")
  146. try:
  147. _ = py_vision.NormalizePad([0.50, 0.30, 0.75], [0.18, 0.32, 0.71, 0.72])
  148. except ValueError as e:
  149. logger.info("Got an exception in DE: {}".format(str(e)))
  150. assert str(e) == "Length of mean and std must be equal."
  151. try:
  152. _ = py_vision.NormalizePad([0.50, 0.30, 0.75], [0.18, 0.32, 0.71], 1)
  153. except TypeError as e:
  154. logger.info("Got an exception in DE: {}".format(str(e)))
  155. assert str(e) == "dtype should be string."
  156. try:
  157. _ = py_vision.NormalizePad([0.50, 0.30, 0.75], [0.18, 0.32, 0.71], "")
  158. except ValueError as e:
  159. logger.info("Got an exception in DE: {}".format(str(e)))
  160. assert str(e) == "dtype only support float32 or float16."
  161. def test_normalizepad_exception_invalid_range_py():
  162. """
  163. Test NormalizePad in python transformation: value is not in range [0,1]
  164. expected to raise ValueError
  165. """
  166. logger.info("test_normalizepad_exception_invalid_range_py")
  167. try:
  168. _ = py_vision.NormalizePad([0.75, 1.25, 0.5], [0.1, 0.18, 1.32])
  169. except ValueError as e:
  170. logger.info("Got an exception in DE: {}".format(str(e)))
  171. assert "Input mean_value is not within the required interval of [0.0, 1.0]." in str(e)