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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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.transforms.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(input_columns=["image"], operations=transforms1)
  43. # Second dataset
  44. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  45. data2 = data2.map(input_columns=["image"], operations=[c_vision.Decode()])
  46. image_posterize = []
  47. image_original = []
  48. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  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(input_columns=["image"], operations=transforms1)
  80. # Second dataset
  81. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  82. data2 = data2.map(input_columns=["image"], operations=[c_vision.Decode()])
  83. image_posterize = []
  84. image_original = []
  85. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  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_exception_bit():
  97. """
  98. Test RandomPosterize: out of range input bits and invalid type
  99. """
  100. logger.info("test_random_posterize_exception_bit")
  101. # Test max > 8
  102. try:
  103. _ = c_vision.RandomPosterize((1, 9))
  104. except ValueError as e:
  105. logger.info("Got an exception in DE: {}".format(str(e)))
  106. assert str(e) == "Input is not within the required interval of (1 to 8)."
  107. # Test min < 1
  108. try:
  109. _ = c_vision.RandomPosterize((0, 7))
  110. except ValueError as e:
  111. logger.info("Got an exception in DE: {}".format(str(e)))
  112. assert str(e) == "Input is not within the required interval of (1 to 8)."
  113. # Test max < min
  114. try:
  115. _ = c_vision.RandomPosterize((8, 1))
  116. except ValueError as e:
  117. logger.info("Got an exception in DE: {}".format(str(e)))
  118. assert str(e) == "Input is not within the required interval of (1 to 8)."
  119. # Test wrong type (not uint8)
  120. try:
  121. _ = c_vision.RandomPosterize(1.1)
  122. except TypeError as e:
  123. logger.info("Got an exception in DE: {}".format(str(e)))
  124. assert str(e) == "Argument bits with value 1.1 is not of type (<class 'list'>, <class 'tuple'>, <class 'int'>)."
  125. # Test wrong number of bits
  126. try:
  127. _ = c_vision.RandomPosterize((1, 1, 1))
  128. except TypeError as e:
  129. logger.info("Got an exception in DE: {}".format(str(e)))
  130. assert str(e) == "Size of bits should be a single integer or a list/tuple (min, max) of length 2."
  131. def test_rescale_with_random_posterize():
  132. """
  133. Test RandomPosterize: only support CV_8S/CV_8U
  134. """
  135. logger.info("test_rescale_with_random_posterize")
  136. DATA_DIR_10 = "../data/dataset/testCifar10Data"
  137. dataset = ds.Cifar10Dataset(DATA_DIR_10)
  138. rescale_op = c_vision.Rescale((1.0 / 255.0), 0.0)
  139. dataset = dataset.map(input_columns=["image"], operations=rescale_op)
  140. random_posterize_op = c_vision.RandomPosterize((4, 8))
  141. dataset = dataset.map(input_columns=["image"], operations=random_posterize_op, num_parallel_workers=1)
  142. try:
  143. _ = dataset.output_shapes()
  144. except RuntimeError as e:
  145. logger.info("Got an exception in DE: {}".format(str(e)))
  146. assert "Input image data type can not be float" in str(e)
  147. if __name__ == "__main__":
  148. test_random_posterize_op_c(plot=False, run_golden=False)
  149. test_random_posterize_op_fixed_point_c(plot=False)
  150. test_random_posterize_exception_bit()
  151. test_rescale_with_random_posterize()