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_linear_transformation.py 8.0 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 LinearTransformation op in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.transforms.vision.py_transforms as py_vision
  21. from mindspore import log as logger
  22. from util import diff_mse, visualize_list, save_and_check_md5
  23. GENERATE_GOLDEN = False
  24. DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  25. SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
  26. def test_linear_transformation_op(plot=False):
  27. """
  28. Test LinearTransformation op: verify if images transform correctly
  29. """
  30. logger.info("test_linear_transformation_01")
  31. # Initialize parameters
  32. height = 50
  33. weight = 50
  34. dim = 3 * height * weight
  35. transformation_matrix = np.eye(dim)
  36. mean_vector = np.zeros(dim)
  37. # Define operations
  38. transforms = [
  39. py_vision.Decode(),
  40. py_vision.CenterCrop([height, weight]),
  41. py_vision.ToTensor()
  42. ]
  43. transform = py_vision.ComposeOp(transforms)
  44. # First dataset
  45. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  46. data1 = data1.map(input_columns=["image"], operations=transform())
  47. # Note: if transformation matrix is diagonal matrix with all 1 in diagonal,
  48. # the output matrix in expected to be the same as the input matrix.
  49. data1 = data1.map(input_columns=["image"],
  50. operations=py_vision.LinearTransformation(transformation_matrix, mean_vector))
  51. # Second dataset
  52. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  53. data2 = data2.map(input_columns=["image"], operations=transform())
  54. image_transformed = []
  55. image = []
  56. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  57. image1 = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  58. image2 = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  59. image_transformed.append(image1)
  60. image.append(image2)
  61. mse = diff_mse(image1, image2)
  62. assert mse == 0
  63. if plot:
  64. visualize_list(image, image_transformed)
  65. def test_linear_transformation_md5_01():
  66. """
  67. Test LinearTransformation op: valid params (transformation_matrix, mean_vector)
  68. Expected to pass
  69. """
  70. logger.info("test_linear_transformation_md5_01")
  71. # Initialize parameters
  72. height = 50
  73. weight = 50
  74. dim = 3 * height * weight
  75. transformation_matrix = np.ones([dim, dim])
  76. mean_vector = np.zeros(dim)
  77. # Generate dataset
  78. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  79. transforms = [
  80. py_vision.Decode(),
  81. py_vision.CenterCrop([height, weight]),
  82. py_vision.ToTensor(),
  83. py_vision.LinearTransformation(transformation_matrix, mean_vector)
  84. ]
  85. transform = py_vision.ComposeOp(transforms)
  86. data1 = data1.map(input_columns=["image"], operations=transform())
  87. # Compare with expected md5 from images
  88. filename = "linear_transformation_01_result.npz"
  89. save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
  90. def test_linear_transformation_md5_02():
  91. """
  92. Test LinearTransformation op: transformation_matrix is not provided
  93. Expected to raise ValueError
  94. """
  95. logger.info("test_linear_transformation_md5_02")
  96. # Initialize parameters
  97. height = 50
  98. weight = 50
  99. dim = 3 * height * weight
  100. mean_vector = np.zeros(dim)
  101. # Generate dataset
  102. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  103. try:
  104. transforms = [
  105. py_vision.Decode(),
  106. py_vision.CenterCrop([height, weight]),
  107. py_vision.ToTensor(),
  108. py_vision.LinearTransformation(None, mean_vector)
  109. ]
  110. transform = py_vision.ComposeOp(transforms)
  111. data1 = data1.map(input_columns=["image"], operations=transform())
  112. except ValueError as e:
  113. logger.info("Got an exception in DE: {}".format(str(e)))
  114. assert "not provided" in str(e)
  115. def test_linear_transformation_md5_03():
  116. """
  117. Test LinearTransformation op: mean_vector is not provided
  118. Expected to raise ValueError
  119. """
  120. logger.info("test_linear_transformation_md5_03")
  121. # Initialize parameters
  122. height = 50
  123. weight = 50
  124. dim = 3 * height * weight
  125. transformation_matrix = np.ones([dim, dim])
  126. # Generate dataset
  127. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  128. try:
  129. transforms = [
  130. py_vision.Decode(),
  131. py_vision.CenterCrop([height, weight]),
  132. py_vision.ToTensor(),
  133. py_vision.LinearTransformation(transformation_matrix, None)
  134. ]
  135. transform = py_vision.ComposeOp(transforms)
  136. data1 = data1.map(input_columns=["image"], operations=transform())
  137. except ValueError as e:
  138. logger.info("Got an exception in DE: {}".format(str(e)))
  139. assert "not provided" in str(e)
  140. def test_linear_transformation_md5_04():
  141. """
  142. Test LinearTransformation op: transformation_matrix is not a square matrix
  143. Expected to raise ValueError
  144. """
  145. logger.info("test_linear_transformation_md5_04")
  146. # Initialize parameters
  147. height = 50
  148. weight = 50
  149. dim = 3 * height * weight
  150. transformation_matrix = np.ones([dim, dim - 1])
  151. mean_vector = np.zeros(dim)
  152. # Generate dataset
  153. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  154. try:
  155. transforms = [
  156. py_vision.Decode(),
  157. py_vision.CenterCrop([height, weight]),
  158. py_vision.ToTensor(),
  159. py_vision.LinearTransformation(transformation_matrix, mean_vector)
  160. ]
  161. transform = py_vision.ComposeOp(transforms)
  162. data1 = data1.map(input_columns=["image"], operations=transform())
  163. except ValueError as e:
  164. logger.info("Got an exception in DE: {}".format(str(e)))
  165. assert "square matrix" in str(e)
  166. def test_linear_transformation_md5_05():
  167. """
  168. Test LinearTransformation op: mean_vector does not match dimension of transformation_matrix
  169. Expected to raise ValueError
  170. """
  171. logger.info("test_linear_transformation_md5_05")
  172. # Initialize parameters
  173. height = 50
  174. weight = 50
  175. dim = 3 * height * weight
  176. transformation_matrix = np.ones([dim, dim])
  177. mean_vector = np.zeros(dim-1)
  178. # Generate dataset
  179. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  180. try:
  181. transforms = [
  182. py_vision.Decode(),
  183. py_vision.CenterCrop([height, weight]),
  184. py_vision.ToTensor(),
  185. py_vision.LinearTransformation(transformation_matrix, mean_vector)
  186. ]
  187. transform = py_vision.ComposeOp(transforms)
  188. data1 = data1.map(input_columns=["image"], operations=transform())
  189. except ValueError as e:
  190. logger.info("Got an exception in DE: {}".format(str(e)))
  191. assert "should match" in str(e)
  192. if __name__ == '__main__':
  193. test_linear_transformation_op(True)
  194. test_linear_transformation_md5_01()
  195. test_linear_transformation_md5_02()
  196. test_linear_transformation_md5_03()
  197. test_linear_transformation_md5_04()
  198. test_linear_transformation_md5_05()