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_posterize.py 8.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 RandomPosterize op in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.vision.c_transforms as c_vision
  21. from mindspore import log as logger
  22. from util import visualize_list, save_and_check_md5, \
  23. config_get_set_seed, config_get_set_num_parallel_workers, diff_mse
  24. GENERATE_GOLDEN = False
  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. def test_random_posterize_op_c(plot=False, run_golden=False):
  28. """
  29. Test RandomPosterize in C transformations (uses assertion on mse as using md5 could have jpeg decoding
  30. inconsistencies)
  31. """
  32. logger.info("test_random_posterize_op_c")
  33. original_seed = config_get_set_seed(55)
  34. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  35. # define map operations
  36. transforms1 = [
  37. c_vision.Decode(),
  38. c_vision.RandomPosterize((1, 8))
  39. ]
  40. # First dataset
  41. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  42. data1 = data1.map(operations=transforms1, input_columns=["image"])
  43. # Second dataset
  44. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  45. data2 = data2.map(operations=[c_vision.Decode()], input_columns=["image"])
  46. image_posterize = []
  47. image_original = []
  48. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  49. image1 = item1["image"]
  50. image2 = item2["image"]
  51. image_posterize.append(image1)
  52. image_original.append(image2)
  53. # check mse as md5 can be inconsistent.
  54. # mse = 2.9668956 is calculated from
  55. # a thousand runs of diff_mse(np.array(image_original), np.array(image_posterize)) that all produced the same mse.
  56. # allow for an error of 0.0000005
  57. assert abs(2.9668956 - diff_mse(np.array(image_original), np.array(image_posterize))) <= 0.0000005
  58. if run_golden:
  59. # check results with md5 comparison
  60. filename = "random_posterize_01_result_c.npz"
  61. save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
  62. if plot:
  63. visualize_list(image_original, image_posterize)
  64. # Restore configuration
  65. ds.config.set_seed(original_seed)
  66. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  67. def test_random_posterize_op_fixed_point_c(plot=False, run_golden=True):
  68. """
  69. Test RandomPosterize in C transformations with fixed point
  70. """
  71. logger.info("test_random_posterize_op_c")
  72. # define map operations
  73. transforms1 = [
  74. c_vision.Decode(),
  75. c_vision.RandomPosterize(1)
  76. ]
  77. # First dataset
  78. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  79. data1 = data1.map(operations=transforms1, input_columns=["image"])
  80. # Second dataset
  81. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  82. data2 = data2.map(operations=[c_vision.Decode()], input_columns=["image"])
  83. image_posterize = []
  84. image_original = []
  85. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  86. image1 = item1["image"]
  87. image2 = item2["image"]
  88. image_posterize.append(image1)
  89. image_original.append(image2)
  90. if run_golden:
  91. # check results with md5 comparison
  92. filename = "random_posterize_fixed_point_01_result_c.npz"
  93. save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
  94. if plot:
  95. visualize_list(image_original, image_posterize)
  96. def test_random_posterize_default_c_md5(plot=False, run_golden=True):
  97. """
  98. Test RandomPosterize C Op (default params) with md5 comparison
  99. """
  100. logger.info("test_random_posterize_default_c_md5")
  101. original_seed = config_get_set_seed(5)
  102. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  103. # define map operations
  104. transforms1 = [
  105. c_vision.Decode(),
  106. c_vision.RandomPosterize()
  107. ]
  108. # First dataset
  109. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  110. data1 = data1.map(operations=transforms1, input_columns=["image"])
  111. # Second dataset
  112. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  113. data2 = data2.map(operations=[c_vision.Decode()], input_columns=["image"])
  114. image_posterize = []
  115. image_original = []
  116. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  117. image1 = item1["image"]
  118. image2 = item2["image"]
  119. image_posterize.append(image1)
  120. image_original.append(image2)
  121. if run_golden:
  122. # check results with md5 comparison
  123. filename = "random_posterize_01_default_result_c.npz"
  124. save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
  125. if plot:
  126. visualize_list(image_original, image_posterize)
  127. # Restore configuration
  128. ds.config.set_seed(original_seed)
  129. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  130. def test_random_posterize_exception_bit():
  131. """
  132. Test RandomPosterize: out of range input bits and invalid type
  133. """
  134. logger.info("test_random_posterize_exception_bit")
  135. # Test max > 8
  136. try:
  137. _ = c_vision.RandomPosterize((1, 9))
  138. except ValueError as e:
  139. logger.info("Got an exception in DE: {}".format(str(e)))
  140. assert str(e) == "Input is not within the required interval of (1 to 8)."
  141. # Test min < 1
  142. try:
  143. _ = c_vision.RandomPosterize((0, 7))
  144. except ValueError as e:
  145. logger.info("Got an exception in DE: {}".format(str(e)))
  146. assert str(e) == "Input is not within the required interval of (1 to 8)."
  147. # Test max < min
  148. try:
  149. _ = c_vision.RandomPosterize((8, 1))
  150. except ValueError as e:
  151. logger.info("Got an exception in DE: {}".format(str(e)))
  152. assert str(e) == "Input is not within the required interval of (1 to 8)."
  153. # Test wrong type (not uint8)
  154. try:
  155. _ = c_vision.RandomPosterize(1.1)
  156. except TypeError as e:
  157. logger.info("Got an exception in DE: {}".format(str(e)))
  158. assert str(e) == "Argument bits with value 1.1 is not of type (<class 'list'>, <class 'tuple'>, <class 'int'>)."
  159. # Test wrong number of bits
  160. try:
  161. _ = c_vision.RandomPosterize((1, 1, 1))
  162. except TypeError as e:
  163. logger.info("Got an exception in DE: {}".format(str(e)))
  164. assert str(e) == "Size of bits should be a single integer or a list/tuple (min, max) of length 2."
  165. def test_rescale_with_random_posterize():
  166. """
  167. Test RandomPosterize: only support CV_8S/CV_8U
  168. """
  169. logger.info("test_rescale_with_random_posterize")
  170. DATA_DIR_10 = "../data/dataset/testCifar10Data"
  171. dataset = ds.Cifar10Dataset(DATA_DIR_10)
  172. rescale_op = c_vision.Rescale((1.0 / 255.0), 0.0)
  173. dataset = dataset.map(operations=rescale_op, input_columns=["image"])
  174. random_posterize_op = c_vision.RandomPosterize((4, 8))
  175. dataset = dataset.map(operations=random_posterize_op, input_columns=["image"], num_parallel_workers=1)
  176. try:
  177. _ = dataset.output_shapes()
  178. except RuntimeError as e:
  179. logger.info("Got an exception in DE: {}".format(str(e)))
  180. assert "Input image data type can not be float" in str(e)
  181. if __name__ == "__main__":
  182. test_random_posterize_op_c(plot=False, run_golden=False)
  183. test_random_posterize_op_fixed_point_c(plot=False)
  184. test_random_posterize_default_c_md5(plot=False)
  185. test_random_posterize_exception_bit()
  186. test_rescale_with_random_posterize()