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.9 kB

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