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_datasets_sbd.py 9.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # Copyright 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. import math
  16. import matplotlib.pyplot as plt
  17. import numpy as np
  18. import pytest
  19. import mindspore.dataset as ds
  20. from mindspore import log as logger
  21. import mindspore.dataset.vision.c_transforms as c_vision
  22. DATASET_DIR = "../data/dataset/testSBData/sbd"
  23. def visualize_dataset(images, labels, task):
  24. """
  25. Helper function to visualize the dataset samples
  26. """
  27. image_num = len(images)
  28. subplot_rows = 1 if task == "Segmentation" else 4
  29. for i in range(image_num):
  30. plt.imshow(images[i])
  31. plt.title('Original')
  32. plt.savefig('./sbd_original_{}.jpg'.format(str(i)))
  33. if task == "Segmentation":
  34. plt.imshow(labels[i])
  35. plt.title(task)
  36. plt.savefig('./sbd_segmentation_{}.jpg'.format(str(i)))
  37. else:
  38. b_num = labels[i].shape[0]
  39. for j in range(b_num):
  40. plt.subplot(subplot_rows, math.ceil(b_num / subplot_rows), j + 1)
  41. plt.imshow(labels[i][j])
  42. plt.savefig('./sbd_boundaries_{}.jpg'.format(str(i)))
  43. plt.close()
  44. def test_sbd_basic01(plot=False):
  45. """
  46. Validate SBDataset with different usage
  47. """
  48. task = 'Segmentation' # Boundaries, Segmentation
  49. data = ds.SBDataset(DATASET_DIR, task=task, usage='all', shuffle=False, decode=True)
  50. count = 0
  51. images_list = []
  52. task_list = []
  53. for item in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  54. images_list.append(item['image'])
  55. task_list.append(item['task'])
  56. count = count + 1
  57. assert count == 6
  58. if plot:
  59. visualize_dataset(images_list, task_list, task)
  60. data2 = ds.SBDataset(DATASET_DIR, task=task, usage='train', shuffle=False, decode=False)
  61. count = 0
  62. for item in data2.create_dict_iterator(num_epochs=1, output_numpy=True):
  63. count = count + 1
  64. assert count == 4
  65. data3 = ds.SBDataset(DATASET_DIR, task=task, usage='val', shuffle=False, decode=False)
  66. count = 0
  67. for item in data3.create_dict_iterator(num_epochs=1, output_numpy=True):
  68. count = count + 1
  69. assert count == 2
  70. def test_sbd_basic02():
  71. """
  72. Validate SBDataset with repeat and batch operation
  73. """
  74. # Boundaries, Segmentation
  75. # case 1: test num_samples
  76. data1 = ds.SBDataset(DATASET_DIR, task='Boundaries', usage='train', num_samples=3, shuffle=False)
  77. num_iter1 = 0
  78. for _ in data1.create_dict_iterator(num_epochs=1):
  79. num_iter1 += 1
  80. assert num_iter1 == 3
  81. # case 2: test repeat
  82. data2 = ds.SBDataset(DATASET_DIR, task='Boundaries', usage='train', num_samples=4, shuffle=False)
  83. data2 = data2.repeat(5)
  84. num_iter2 = 0
  85. for _ in data2.create_dict_iterator(num_epochs=1):
  86. num_iter2 += 1
  87. assert num_iter2 == 20
  88. # case 3: test batch with drop_remainder=False
  89. data3 = ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', shuffle=False, decode=True)
  90. resize_op = c_vision.Resize((100, 100))
  91. data3 = data3.map(operations=resize_op, input_columns=["image"], num_parallel_workers=1)
  92. data3 = data3.map(operations=resize_op, input_columns=["task"], num_parallel_workers=1)
  93. assert data3.get_dataset_size() == 4
  94. assert data3.get_batch_size() == 1
  95. data3 = data3.batch(batch_size=3) # drop_remainder is default to be False
  96. assert data3.get_dataset_size() == 2
  97. assert data3.get_batch_size() == 3
  98. num_iter3 = 0
  99. for _ in data3.create_dict_iterator(num_epochs=1):
  100. num_iter3 += 1
  101. assert num_iter3 == 2
  102. # case 4: test batch with drop_remainder=True
  103. data4 = ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', shuffle=False, decode=True)
  104. resize_op = c_vision.Resize((100, 100))
  105. data4 = data4.map(operations=resize_op, input_columns=["image"], num_parallel_workers=1)
  106. data4 = data4.map(operations=resize_op, input_columns=["task"], num_parallel_workers=1)
  107. assert data4.get_dataset_size() == 4
  108. assert data4.get_batch_size() == 1
  109. data4 = data4.batch(batch_size=3, drop_remainder=True) # the rest of incomplete batch will be dropped
  110. assert data4.get_dataset_size() == 1
  111. assert data4.get_batch_size() == 3
  112. num_iter4 = 0
  113. for _ in data4.create_dict_iterator(num_epochs=1):
  114. num_iter4 += 1
  115. assert num_iter4 == 1
  116. def test_sbd_sequential_sampler():
  117. """
  118. Test SBDataset with SequentialSampler
  119. """
  120. logger.info("Test SBDataset Op with SequentialSampler")
  121. num_samples = 5
  122. sampler = ds.SequentialSampler(num_samples=num_samples)
  123. data1 = ds.SBDataset(DATASET_DIR, task='Segmentation', usage='all', sampler=sampler)
  124. data2 = ds.SBDataset(DATASET_DIR, task='Segmentation', usage='all', shuffle=False, num_samples=num_samples)
  125. num_iter = 0
  126. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  127. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  128. np.testing.assert_array_equal(item1["task"], item2["task"])
  129. num_iter += 1
  130. assert num_iter == num_samples
  131. def test_sbd_exception():
  132. """
  133. Validate SBDataset with error parameters
  134. """
  135. error_msg_1 = "sampler and shuffle cannot be specified at the same time"
  136. with pytest.raises(RuntimeError, match=error_msg_1):
  137. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', shuffle=False, sampler=ds.PKSampler(3))
  138. error_msg_2 = "sampler and sharding cannot be specified at the same time"
  139. with pytest.raises(RuntimeError, match=error_msg_2):
  140. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', num_shards=2, shard_id=0,
  141. sampler=ds.PKSampler(3))
  142. error_msg_3 = "num_shards is specified and currently requires shard_id as well"
  143. with pytest.raises(RuntimeError, match=error_msg_3):
  144. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', num_shards=10)
  145. error_msg_4 = "shard_id is specified but num_shards is not"
  146. with pytest.raises(RuntimeError, match=error_msg_4):
  147. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', shard_id=0)
  148. error_msg_5 = "Input shard_id is not within the required interval"
  149. with pytest.raises(ValueError, match=error_msg_5):
  150. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', num_shards=5, shard_id=-1)
  151. with pytest.raises(ValueError, match=error_msg_5):
  152. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', num_shards=5, shard_id=5)
  153. with pytest.raises(ValueError, match=error_msg_5):
  154. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', num_shards=2, shard_id=5)
  155. error_msg_6 = "num_parallel_workers exceeds"
  156. with pytest.raises(ValueError, match=error_msg_6):
  157. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', shuffle=False, num_parallel_workers=0)
  158. with pytest.raises(ValueError, match=error_msg_6):
  159. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', shuffle=False, num_parallel_workers=256)
  160. with pytest.raises(ValueError, match=error_msg_6):
  161. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', shuffle=False, num_parallel_workers=-2)
  162. error_msg_7 = "Argument shard_id"
  163. with pytest.raises(TypeError, match=error_msg_7):
  164. ds.SBDataset(DATASET_DIR, task='Segmentation', usage='train', num_shards=2, shard_id="0")
  165. def test_sbd_usage():
  166. """
  167. Validate SBDataset image readings
  168. """
  169. def test_config(usage):
  170. try:
  171. data = ds.SBDataset(DATASET_DIR, task='Segmentation', usage=usage)
  172. num_rows = 0
  173. for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  174. num_rows += 1
  175. except (ValueError, TypeError, RuntimeError) as e:
  176. return str(e)
  177. return num_rows
  178. assert test_config("train") == 4
  179. assert test_config("train_noval") == 4
  180. assert test_config("val") == 2
  181. assert test_config("all") == 6
  182. assert "usage is not within the valid set of ['train', 'val', 'train_noval', 'all']" in test_config("invalid")
  183. assert "Argument usage with value ['list'] is not of type [<class 'str'>]" in test_config(["list"])
  184. if __name__ == "__main__":
  185. test_sbd_basic01()
  186. test_sbd_basic02()
  187. test_sbd_sequential_sampler()
  188. test_sbd_exception()
  189. test_sbd_usage()