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_ten_crop.py 6.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. Testing TenCrop in DE
  16. """
  17. import pytest
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.transforms.py_transforms
  21. import mindspore.dataset.vision.py_transforms as vision
  22. from mindspore import log as logger
  23. from util import visualize_list, save_and_check_md5
  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 util_test_ten_crop(crop_size, vertical_flip=False, plot=False):
  28. """
  29. Utility function for testing TenCrop. Input arguments are given by other tests
  30. """
  31. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  32. transforms_1 = [
  33. vision.Decode(),
  34. vision.ToTensor(),
  35. ]
  36. transform_1 = mindspore.dataset.transforms.py_transforms.Compose(transforms_1)
  37. data1 = data1.map(operations=transform_1, input_columns=["image"])
  38. # Second dataset
  39. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  40. transforms_2 = [
  41. vision.Decode(),
  42. vision.TenCrop(crop_size, use_vertical_flip=vertical_flip),
  43. lambda images: np.stack([vision.ToTensor()(image) for image in images]) # 4D stack of 10 images
  44. ]
  45. transform_2 = mindspore.dataset.transforms.py_transforms.Compose(transforms_2)
  46. data2 = data2.map(operations=transform_2, input_columns=["image"])
  47. num_iter = 0
  48. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  49. num_iter += 1
  50. image_1 = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  51. image_2 = item2["image"]
  52. logger.info("shape of image_1: {}".format(image_1.shape))
  53. logger.info("shape of image_2: {}".format(image_2.shape))
  54. logger.info("dtype of image_1: {}".format(image_1.dtype))
  55. logger.info("dtype of image_2: {}".format(image_2.dtype))
  56. if plot:
  57. visualize_list(np.array([image_1] * 10), (image_2 * 255).astype(np.uint8).transpose(0, 2, 3, 1))
  58. # The output data should be of a 4D tensor shape, a stack of 10 images.
  59. assert len(image_2.shape) == 4
  60. assert image_2.shape[0] == 10
  61. def test_ten_crop_op_square(plot=False):
  62. """
  63. Tests TenCrop for a square crop
  64. """
  65. logger.info("test_ten_crop_op_square")
  66. util_test_ten_crop(200, plot=plot)
  67. def test_ten_crop_op_rectangle(plot=False):
  68. """
  69. Tests TenCrop for a rectangle crop
  70. """
  71. logger.info("test_ten_crop_op_rectangle")
  72. util_test_ten_crop((200, 150), plot=plot)
  73. def test_ten_crop_op_vertical_flip(plot=False):
  74. """
  75. Tests TenCrop with vertical flip set to True
  76. """
  77. logger.info("test_ten_crop_op_vertical_flip")
  78. util_test_ten_crop(200, vertical_flip=True, plot=plot)
  79. def test_ten_crop_md5():
  80. """
  81. Tests TenCrops for giving the same results in multiple runs.
  82. Since TenCrop is a deterministic function, we expect it to return the same result for a specific input every time
  83. """
  84. logger.info("test_ten_crop_md5")
  85. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  86. transforms_2 = [
  87. vision.Decode(),
  88. vision.TenCrop((200, 100), use_vertical_flip=True),
  89. lambda images: np.stack([vision.ToTensor()(image) for image in images]) # 4D stack of 10 images
  90. ]
  91. transform_2 = mindspore.dataset.transforms.py_transforms.Compose(transforms_2)
  92. data2 = data2.map(operations=transform_2, input_columns=["image"])
  93. # Compare with expected md5 from images
  94. filename = "ten_crop_01_result.npz"
  95. save_and_check_md5(data2, filename, generate_golden=GENERATE_GOLDEN)
  96. def test_ten_crop_list_size_error_msg():
  97. """
  98. Tests TenCrop error message when the size arg has more than 2 elements
  99. """
  100. logger.info("test_ten_crop_list_size_error_msg")
  101. with pytest.raises(TypeError) as info:
  102. _ = [
  103. vision.Decode(),
  104. vision.TenCrop([200, 200, 200]),
  105. lambda images: np.stack([vision.ToTensor()(image) for image in images]) # 4D stack of 10 images
  106. ]
  107. error_msg = "Size should be a single integer or a list/tuple (h, w) of length 2."
  108. assert error_msg == str(info.value)
  109. def test_ten_crop_invalid_size_error_msg():
  110. """
  111. Tests TenCrop error message when the size arg is not positive
  112. """
  113. logger.info("test_ten_crop_invalid_size_error_msg")
  114. with pytest.raises(ValueError) as info:
  115. _ = [
  116. vision.Decode(),
  117. vision.TenCrop(0),
  118. lambda images: np.stack([vision.ToTensor()(image) for image in images]) # 4D stack of 10 images
  119. ]
  120. error_msg = "Input is not within the required interval of (1 to 16777216)."
  121. assert error_msg == str(info.value)
  122. with pytest.raises(ValueError) as info:
  123. _ = [
  124. vision.Decode(),
  125. vision.TenCrop(-10),
  126. lambda images: np.stack([vision.ToTensor()(image) for image in images]) # 4D stack of 10 images
  127. ]
  128. assert error_msg == str(info.value)
  129. def test_ten_crop_wrong_img_error_msg():
  130. """
  131. Tests TenCrop error message when the image is not in the correct format.
  132. """
  133. logger.info("test_ten_crop_wrong_img_error_msg")
  134. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  135. transforms = [
  136. vision.Decode(),
  137. vision.TenCrop(200),
  138. vision.ToTensor()
  139. ]
  140. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  141. data = data.map(operations=transform, input_columns=["image"])
  142. with pytest.raises(RuntimeError) as info:
  143. data.create_tuple_iterator(num_epochs=1).get_next()
  144. error_msg = "TypeError: img should be PIL image or NumPy array. Got <class 'tuple'>"
  145. # error msg comes from ToTensor()
  146. assert error_msg in str(info.value)
  147. if __name__ == "__main__":
  148. test_ten_crop_op_square(plot=True)
  149. test_ten_crop_op_rectangle(plot=True)
  150. test_ten_crop_op_vertical_flip(plot=True)
  151. test_ten_crop_md5()
  152. test_ten_crop_list_size_error_msg()
  153. test_ten_crop_invalid_size_error_msg()
  154. test_ten_crop_wrong_img_error_msg()