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_HWC2CHW.py 6.7 kB

6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # Copyright 2020-2021 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 HWC2CHW op in DE
  17. """
  18. import numpy as np
  19. import pytest
  20. import mindspore.dataset as ds
  21. import mindspore.dataset.transforms.py_transforms
  22. import mindspore.dataset.vision.c_transforms as c_vision
  23. import mindspore.dataset.vision.py_transforms as py_vision
  24. from mindspore import log as logger
  25. from util import diff_mse, visualize_list, save_and_check_md5
  26. GENERATE_GOLDEN = False
  27. DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  28. SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
  29. def test_HWC2CHW_callable():
  30. """
  31. Test HWC2CHW is callable
  32. """
  33. logger.info("Test HWC2CHW callable")
  34. img = np.zeros([50, 50, 3])
  35. assert img.shape == (50, 50, 3)
  36. # test one tensor
  37. img1 = c_vision.HWC2CHW()(img)
  38. assert img1.shape == (3, 50, 50)
  39. # test one tensor with 5 channels
  40. img2 = np.zeros([50, 50, 5])
  41. assert img2.shape == (50, 50, 5)
  42. img3 = c_vision.HWC2CHW()(img2)
  43. assert img3.shape == (5, 50, 50)
  44. # test input multiple tensors
  45. with pytest.raises(RuntimeError) as info:
  46. imgs = [img, img]
  47. _ = c_vision.HWC2CHW()(*imgs)
  48. assert "The op is OneToOne, can only accept one tensor as input." in str(info.value)
  49. with pytest.raises(RuntimeError) as info:
  50. _ = c_vision.HWC2CHW()(img, img)
  51. assert "The op is OneToOne, can only accept one tensor as input." in str(info.value)
  52. def test_HWC2CHW_multi_channels():
  53. """
  54. Feature: Test HWC2CHW feature
  55. Description: The input is a HWC format array with 5 channels
  56. Expectation: success
  57. """
  58. logger.info("Test HWC2CHW with data of 5 channels")
  59. # create numpy array in HWC format with shape (4, 2, 5) like a fake image with 5 channels
  60. raw_data = np.random.rand(4, 2, 5).astype(np.float32)
  61. expect_output = np.transpose(raw_data, (2, 0, 1))
  62. # NumpySliceDataset support accept data stored in list, tuple etc, here only one row data in list.
  63. input_data = np.array([raw_data])
  64. dataset = ds.NumpySlicesDataset(input_data, column_names=["col1"], shuffle=False)
  65. hwc2chw = c_vision.HWC2CHW()
  66. dataset = dataset.map(hwc2chw, input_columns=["col1"])
  67. for item in dataset.create_tuple_iterator(output_numpy=True):
  68. assert np.allclose(item[0], expect_output)
  69. def test_HWC2CHW(plot=False):
  70. """
  71. Test HWC2CHW
  72. """
  73. logger.info("Test HWC2CHW")
  74. # First dataset
  75. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  76. decode_op = c_vision.Decode()
  77. hwc2chw_op = c_vision.HWC2CHW()
  78. data1 = data1.map(operations=decode_op, input_columns=["image"])
  79. data1 = data1.map(operations=hwc2chw_op, input_columns=["image"])
  80. # Second dataset
  81. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  82. data2 = data2.map(operations=decode_op, input_columns=["image"])
  83. image_transposed = []
  84. image = []
  85. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  86. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  87. transposed_item = item1["image"].copy()
  88. original_item = item2["image"].copy()
  89. image_transposed.append(transposed_item.transpose(1, 2, 0))
  90. image.append(original_item)
  91. # check if the shape of data is transposed correctly
  92. # transpose the original image from shape (H,W,C) to (C,H,W)
  93. mse = diff_mse(transposed_item, original_item.transpose(2, 0, 1))
  94. assert mse == 0
  95. if plot:
  96. visualize_list(image, image_transposed)
  97. def test_HWC2CHW_md5():
  98. """
  99. Test HWC2CHW(md5)
  100. """
  101. logger.info("Test HWC2CHW with md5 comparison")
  102. # First dataset
  103. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  104. decode_op = c_vision.Decode()
  105. hwc2chw_op = c_vision.HWC2CHW()
  106. data1 = data1.map(operations=decode_op, input_columns=["image"])
  107. data1 = data1.map(operations=hwc2chw_op, input_columns=["image"])
  108. # Compare with expected md5 from images
  109. filename = "HWC2CHW_01_result.npz"
  110. save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
  111. def test_HWC2CHW_comp(plot=False):
  112. """
  113. Test HWC2CHW between python and c image augmentation
  114. """
  115. logger.info("Test HWC2CHW with c_transform and py_transform comparison")
  116. # First dataset
  117. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  118. decode_op = c_vision.Decode()
  119. hwc2chw_op = c_vision.HWC2CHW()
  120. data1 = data1.map(operations=decode_op, input_columns=["image"])
  121. data1 = data1.map(operations=hwc2chw_op, input_columns=["image"])
  122. # Second dataset
  123. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  124. transforms = [
  125. py_vision.Decode(),
  126. py_vision.ToTensor(),
  127. py_vision.HWC2CHW()
  128. ]
  129. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  130. data2 = data2.map(operations=transform, input_columns=["image"])
  131. image_c_transposed = []
  132. image_py_transposed = []
  133. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  134. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  135. c_image = item1["image"]
  136. py_image = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  137. # Compare images between that applying c_transform and py_transform
  138. mse = diff_mse(py_image, c_image)
  139. # Note: The images aren't exactly the same due to rounding error
  140. assert mse < 0.001
  141. image_c_transposed.append(c_image.transpose(1, 2, 0))
  142. image_py_transposed.append(py_image.transpose(1, 2, 0))
  143. if plot:
  144. visualize_list(image_c_transposed, image_py_transposed, visualize_mode=2)
  145. if __name__ == '__main__':
  146. test_HWC2CHW_callable()
  147. test_HWC2CHW_multi_channels()
  148. test_HWC2CHW(True)
  149. test_HWC2CHW_md5()
  150. test_HWC2CHW_comp(True)