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

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