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

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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.fromfile("../data/dataset/apple.jpg", dtype=np.uint8)
  35. logger.info("Image.type: {}, Image.shape: {}".format(type(img), img.shape))
  36. img = c_vision.Decode()(img)
  37. assert img.shape == (2268, 4032, 3)
  38. # test one tensor
  39. img1 = c_vision.HWC2CHW()(img)
  40. assert img1.shape == (3, 2268, 4032)
  41. # test input multiple tensors
  42. with pytest.raises(RuntimeError) as info:
  43. imgs = [img, img]
  44. _ = c_vision.HWC2CHW()(*imgs)
  45. assert "The op is OneToOne, can only accept one tensor as input." in str(info.value)
  46. with pytest.raises(RuntimeError) as info:
  47. _ = c_vision.HWC2CHW()(img, img)
  48. assert "The op is OneToOne, can only accept one tensor as input." in str(info.value)
  49. def test_HWC2CHW(plot=False):
  50. """
  51. Test HWC2CHW
  52. """
  53. logger.info("Test HWC2CHW")
  54. # First dataset
  55. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  56. decode_op = c_vision.Decode()
  57. hwc2chw_op = c_vision.HWC2CHW()
  58. data1 = data1.map(operations=decode_op, input_columns=["image"])
  59. data1 = data1.map(operations=hwc2chw_op, input_columns=["image"])
  60. # Second dataset
  61. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  62. data2 = data2.map(operations=decode_op, input_columns=["image"])
  63. image_transposed = []
  64. image = []
  65. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  66. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  67. transposed_item = item1["image"].copy()
  68. original_item = item2["image"].copy()
  69. image_transposed.append(transposed_item.transpose(1, 2, 0))
  70. image.append(original_item)
  71. # check if the shape of data is transposed correctly
  72. # transpose the original image from shape (H,W,C) to (C,H,W)
  73. mse = diff_mse(transposed_item, original_item.transpose(2, 0, 1))
  74. assert mse == 0
  75. if plot:
  76. visualize_list(image, image_transposed)
  77. def test_HWC2CHW_md5():
  78. """
  79. Test HWC2CHW(md5)
  80. """
  81. logger.info("Test HWC2CHW with md5 comparison")
  82. # First dataset
  83. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  84. decode_op = c_vision.Decode()
  85. hwc2chw_op = c_vision.HWC2CHW()
  86. data1 = data1.map(operations=decode_op, input_columns=["image"])
  87. data1 = data1.map(operations=hwc2chw_op, input_columns=["image"])
  88. # Compare with expected md5 from images
  89. filename = "HWC2CHW_01_result.npz"
  90. save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
  91. def test_HWC2CHW_comp(plot=False):
  92. """
  93. Test HWC2CHW between python and c image augmentation
  94. """
  95. logger.info("Test HWC2CHW with c_transform and py_transform comparison")
  96. # First dataset
  97. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  98. decode_op = c_vision.Decode()
  99. hwc2chw_op = c_vision.HWC2CHW()
  100. data1 = data1.map(operations=decode_op, input_columns=["image"])
  101. data1 = data1.map(operations=hwc2chw_op, input_columns=["image"])
  102. # Second dataset
  103. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  104. transforms = [
  105. py_vision.Decode(),
  106. py_vision.ToTensor(),
  107. py_vision.HWC2CHW()
  108. ]
  109. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  110. data2 = data2.map(operations=transform, input_columns=["image"])
  111. image_c_transposed = []
  112. image_py_transposed = []
  113. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  114. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  115. c_image = item1["image"]
  116. py_image = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  117. # Compare images between that applying c_transform and py_transform
  118. mse = diff_mse(py_image, c_image)
  119. # Note: The images aren't exactly the same due to rounding error
  120. assert mse < 0.001
  121. image_c_transposed.append(c_image.transpose(1, 2, 0))
  122. image_py_transposed.append(py_image.transpose(1, 2, 0))
  123. if plot:
  124. visualize_list(image_c_transposed, image_py_transposed, visualize_mode=2)
  125. if __name__ == '__main__':
  126. test_HWC2CHW_callable()
  127. test_HWC2CHW(True)
  128. test_HWC2CHW_md5()
  129. test_HWC2CHW_comp(True)