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_center_crop.py 6.1 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # Copyright 2019 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 CenterCrop op in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.transforms.py_transforms
  21. import mindspore.dataset.vision.c_transforms as vision
  22. import mindspore.dataset.vision.py_transforms as py_vision
  23. from mindspore import log as logger
  24. from util import diff_mse, visualize_list, save_and_check_md5
  25. GENERATE_GOLDEN = False
  26. DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  27. SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
  28. def test_center_crop_op(height=375, width=375, plot=False):
  29. """
  30. Test CenterCrop
  31. """
  32. logger.info("Test CenterCrop")
  33. # First dataset
  34. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"])
  35. decode_op = vision.Decode()
  36. # 3 images [375, 500] [600, 500] [512, 512]
  37. center_crop_op = vision.CenterCrop([height, width])
  38. data1 = data1.map(operations=decode_op, input_columns=["image"])
  39. data1 = data1.map(operations=center_crop_op, input_columns=["image"])
  40. # Second dataset
  41. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"])
  42. data2 = data2.map(operations=decode_op, input_columns=["image"])
  43. image_cropped = []
  44. image = []
  45. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  46. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  47. image_cropped.append(item1["image"].copy())
  48. image.append(item2["image"].copy())
  49. if plot:
  50. visualize_list(image, image_cropped)
  51. def test_center_crop_md5(height=375, width=375):
  52. """
  53. Test CenterCrop
  54. """
  55. logger.info("Test CenterCrop")
  56. # First dataset
  57. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  58. decode_op = vision.Decode()
  59. # 3 images [375, 500] [600, 500] [512, 512]
  60. center_crop_op = vision.CenterCrop([height, width])
  61. data1 = data1.map(operations=decode_op, input_columns=["image"])
  62. data1 = data1.map(operations=center_crop_op, input_columns=["image"])
  63. # Compare with expected md5 from images
  64. filename = "center_crop_01_result.npz"
  65. save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
  66. def test_center_crop_comp(height=375, width=375, plot=False):
  67. """
  68. Test CenterCrop between python and c image augmentation
  69. """
  70. logger.info("Test CenterCrop")
  71. # First dataset
  72. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  73. decode_op = vision.Decode()
  74. center_crop_op = vision.CenterCrop([height, width])
  75. data1 = data1.map(operations=decode_op, input_columns=["image"])
  76. data1 = data1.map(operations=center_crop_op, input_columns=["image"])
  77. # Second dataset
  78. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  79. transforms = [
  80. py_vision.Decode(),
  81. py_vision.CenterCrop([height, width]),
  82. py_vision.ToTensor()
  83. ]
  84. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  85. data2 = data2.map(operations=transform, input_columns=["image"])
  86. image_c_cropped = []
  87. image_py_cropped = []
  88. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  89. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  90. c_image = item1["image"]
  91. py_image = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  92. # Note: The images aren't exactly the same due to rounding error
  93. assert diff_mse(py_image, c_image) < 0.001
  94. image_c_cropped.append(c_image.copy())
  95. image_py_cropped.append(py_image.copy())
  96. if plot:
  97. visualize_list(image_c_cropped, image_py_cropped, visualize_mode=2)
  98. def test_crop_grayscale(height=375, width=375):
  99. """
  100. Test that centercrop works with pad and grayscale images
  101. """
  102. # Note: image.transpose performs channel swap to allow py transforms to
  103. # work with c transforms
  104. transforms = [
  105. py_vision.Decode(),
  106. py_vision.Grayscale(1),
  107. py_vision.ToTensor(),
  108. (lambda image: (image.transpose(1, 2, 0) * 255).astype(np.uint8))
  109. ]
  110. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  111. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  112. data1 = data1.map(operations=transform, input_columns=["image"])
  113. # If input is grayscale, the output dimensions should be single channel
  114. crop_gray = vision.CenterCrop([height, width])
  115. data1 = data1.map(operations=crop_gray, input_columns=["image"])
  116. for item1 in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  117. c_image = item1["image"]
  118. # Check that the image is grayscale
  119. assert (c_image.ndim == 3 and c_image.shape[2] == 1)
  120. def test_center_crop_errors():
  121. """
  122. Test that CenterCropOp errors with bad input
  123. """
  124. try:
  125. test_center_crop_op(16777216, 16777216)
  126. except RuntimeError as e:
  127. assert "CenterCropOp padding size is more than 3 times the original size." in \
  128. str(e)
  129. if __name__ == "__main__":
  130. test_center_crop_op(600, 600, plot=True)
  131. test_center_crop_op(300, 600)
  132. test_center_crop_op(600, 300)
  133. test_center_crop_md5()
  134. test_center_crop_comp(plot=True)
  135. test_crop_grayscale()