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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. """
  16. Testing SlicePatches Python API
  17. """
  18. import functools
  19. import numpy as np
  20. import mindspore.dataset as ds
  21. import mindspore.dataset.vision.c_transforms as c_vision
  22. import mindspore.dataset.vision.utils as mode
  23. from mindspore import log as logger
  24. from util import diff_mse, visualize_list
  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 test_slice_patches_01(plot=False):
  28. """
  29. slice rgb image(100, 200) to 4 patches
  30. """
  31. slice_to_patches([100, 200], 2, 2, True, plot=plot)
  32. def test_slice_patches_02(plot=False):
  33. """
  34. no op
  35. """
  36. slice_to_patches([100, 200], 1, 1, True, plot=plot)
  37. def test_slice_patches_03(plot=False):
  38. """
  39. slice rgb image(99, 199) to 4 patches in pad mode
  40. """
  41. slice_to_patches([99, 199], 2, 2, True, plot=plot)
  42. def test_slice_patches_04(plot=False):
  43. """
  44. slice rgb image(99, 199) to 4 patches in drop mode
  45. """
  46. slice_to_patches([99, 199], 2, 2, False, plot=plot)
  47. def test_slice_patches_05(plot=False):
  48. """
  49. slice rgb image(99, 199) to 4 patches in pad mode
  50. """
  51. slice_to_patches([99, 199], 2, 2, True, 255, plot=plot)
  52. def slice_to_patches(ori_size, num_h, num_w, pad_or_drop, fill_value=0, plot=False):
  53. """
  54. Tool function for slice patches
  55. """
  56. logger.info("test_slice_patches_pipeline")
  57. cols = ['img' + str(x) for x in range(num_h*num_w)]
  58. # First dataset
  59. dataset1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, shuffle=False)
  60. decode_op = c_vision.Decode()
  61. resize_op = c_vision.Resize(ori_size) # H, W
  62. slice_patches_op = c_vision.SlicePatches(
  63. num_h, num_w, mode.SliceMode.PAD, fill_value)
  64. if not pad_or_drop:
  65. slice_patches_op = c_vision.SlicePatches(
  66. num_h, num_w, mode.SliceMode.DROP)
  67. dataset1 = dataset1.map(operations=decode_op, input_columns=["image"])
  68. dataset1 = dataset1.map(operations=resize_op, input_columns=["image"])
  69. dataset1 = dataset1.map(operations=slice_patches_op,
  70. input_columns=["image"], output_columns=cols, column_order=cols)
  71. # Second dataset
  72. dataset2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, shuffle=False)
  73. dataset2 = dataset2.map(operations=decode_op, input_columns=["image"])
  74. dataset2 = dataset2.map(operations=resize_op, input_columns=["image"])
  75. func_slice_patches = functools.partial(
  76. slice_patches, num_h=num_h, num_w=num_w, pad_or_drop=pad_or_drop, fill_value=fill_value)
  77. dataset2 = dataset2.map(operations=func_slice_patches,
  78. input_columns=["image"], output_columns=cols, column_order=cols)
  79. num_iter = 0
  80. patches_c = []
  81. patches_py = []
  82. for data1, data2 in zip(dataset1.create_dict_iterator(num_epochs=1, output_numpy=True),
  83. dataset2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  84. for x in range(num_h*num_w):
  85. col = "img" + str(x)
  86. mse = diff_mse(data1[col], data2[col])
  87. logger.info("slice_patches_{}, mse: {}".format(num_iter + 1, mse))
  88. assert mse == 0
  89. patches_c.append(data1[col])
  90. patches_py.append(data2[col])
  91. num_iter += 1
  92. if plot:
  93. visualize_list(patches_py, patches_c)
  94. def test_slice_patches_exception_01():
  95. """
  96. Test SlicePatches with invalid parameters
  97. """
  98. logger.info("test_Slice_Patches_exception")
  99. try:
  100. _ = c_vision.SlicePatches(0, 2)
  101. except ValueError as e:
  102. logger.info("Got an exception in SlicePatches: {}".format(str(e)))
  103. assert "Input num_height is not within" in str(e)
  104. try:
  105. _ = c_vision.SlicePatches(2, 0)
  106. except ValueError as e:
  107. logger.info("Got an exception in SlicePatches: {}".format(str(e)))
  108. assert "Input num_width is not within" in str(e)
  109. try:
  110. _ = c_vision.SlicePatches(2, 2, 1)
  111. except TypeError as e:
  112. logger.info("Got an exception in SlicePatches: {}".format(str(e)))
  113. assert "Argument slice_mode with value" in str(e)
  114. try:
  115. _ = c_vision.SlicePatches(2, 2, mode.SliceMode.PAD, -1)
  116. except ValueError as e:
  117. logger.info("Got an exception in SlicePatches: {}".format(str(e)))
  118. assert "Input fill_value is not within" in str(e)
  119. def slice_patches(image, num_h, num_w, pad_or_drop, fill_value):
  120. """ help function which slice patches with numpy """
  121. if num_h == 1 and num_w == 1:
  122. return image
  123. # (H, W, C)
  124. H, W, C = image.shape
  125. patch_h = H // num_h
  126. patch_w = W // num_w
  127. if H % num_h != 0:
  128. if pad_or_drop:
  129. patch_h += 1
  130. if W % num_w != 0:
  131. if pad_or_drop:
  132. patch_w += 1
  133. img = image[:, :, :]
  134. if pad_or_drop:
  135. img = np.full([patch_h*num_h, patch_w*num_w, C], fill_value, dtype=np.uint8)
  136. img[:H, :W] = image[:, :, :]
  137. patches = []
  138. for top in range(num_h):
  139. for left in range(num_w):
  140. patches.append(img[top*patch_h:(top+1)*patch_h,
  141. left*patch_w:(left+1)*patch_w, :])
  142. return (*patches,)
  143. if __name__ == "__main__":
  144. test_slice_patches_01(plot=True)
  145. test_slice_patches_02(plot=True)
  146. test_slice_patches_03(plot=True)
  147. test_slice_patches_04(plot=True)
  148. test_slice_patches_05(plot=True)
  149. test_slice_patches_exception_01()