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

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