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_bounding_box_augment.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. """
  16. Testing the bounding box augment op in DE
  17. """
  18. from util import visualize_with_bounding_boxes, InvalidBBoxType, check_bad_bbox, \
  19. config_get_set_seed, config_get_set_num_parallel_workers, save_and_check_md5
  20. import numpy as np
  21. import mindspore.log as logger
  22. import mindspore.dataset as ds
  23. import mindspore.dataset.transforms.vision.c_transforms as c_vision
  24. GENERATE_GOLDEN = False
  25. DATA_DIR = "../data/dataset/testVOC2012_2"
  26. def fix_annotate(bboxes):
  27. """
  28. Fix annotations to format followed by mindspore.
  29. :param bboxes: in [label, x_min, y_min, w, h, truncate, difficult] format
  30. :return: annotation in [x_min, y_min, w, h, label, truncate, difficult] format
  31. """
  32. for bbox in bboxes:
  33. if bbox.size == 7:
  34. tmp = bbox[0]
  35. bbox[0] = bbox[1]
  36. bbox[1] = bbox[2]
  37. bbox[2] = bbox[3]
  38. bbox[3] = bbox[4]
  39. bbox[4] = tmp
  40. else:
  41. print("ERROR: Invalid Bounding Box size provided")
  42. break
  43. return bboxes
  44. def test_bounding_box_augment_with_rotation_op(plot_vis=False):
  45. """
  46. Test BoundingBoxAugment op (passing rotation op as transform)
  47. Prints images side by side with and without Aug applied + bboxes to compare and test
  48. """
  49. logger.info("test_bounding_box_augment_with_rotation_op")
  50. original_seed = config_get_set_seed(0)
  51. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  52. dataVoc1 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  53. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  54. # Ratio is set to 1 to apply rotation on all bounding boxes.
  55. test_op = c_vision.BoundingBoxAugment(c_vision.RandomRotation(90), 1)
  56. # maps to fix annotations to minddata standard
  57. dataVoc1 = dataVoc1.map(input_columns=["annotation"],
  58. output_columns=["annotation"],
  59. operations=fix_annotate)
  60. dataVoc2 = dataVoc2.map(input_columns=["annotation"],
  61. output_columns=["annotation"],
  62. operations=fix_annotate)
  63. # map to apply ops
  64. dataVoc2 = dataVoc2.map(input_columns=["image", "annotation"],
  65. output_columns=["image", "annotation"],
  66. columns_order=["image", "annotation"],
  67. operations=[test_op])
  68. filename = "bounding_box_augment_rotation_c_result.npz"
  69. save_and_check_md5(dataVoc2, filename, generate_golden=GENERATE_GOLDEN)
  70. unaugSamp, augSamp = [], []
  71. for unAug, Aug in zip(dataVoc1.create_dict_iterator(), dataVoc2.create_dict_iterator()):
  72. unaugSamp.append(unAug)
  73. augSamp.append(Aug)
  74. if plot_vis:
  75. visualize_with_bounding_boxes(unaugSamp, augSamp)
  76. # Restore config setting
  77. ds.config.set_seed(original_seed)
  78. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  79. def test_bounding_box_augment_with_crop_op(plot_vis=False):
  80. """
  81. Test BoundingBoxAugment op (passing crop op as transform)
  82. Prints images side by side with and without Aug applied + bboxes to compare and test
  83. """
  84. logger.info("test_bounding_box_augment_with_crop_op")
  85. original_seed = config_get_set_seed(1)
  86. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  87. dataVoc1 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  88. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  89. # Ratio is set to 1 to apply rotation on all bounding boxes.
  90. test_op = c_vision.BoundingBoxAugment(c_vision.RandomCrop(90), 1)
  91. # maps to fix annotations to minddata standard
  92. dataVoc1 = dataVoc1.map(input_columns=["annotation"],
  93. output_columns=["annotation"],
  94. operations=fix_annotate)
  95. dataVoc2 = dataVoc2.map(input_columns=["annotation"],
  96. output_columns=["annotation"],
  97. operations=fix_annotate)
  98. # map to apply ops
  99. dataVoc2 = dataVoc2.map(input_columns=["image", "annotation"],
  100. output_columns=["image", "annotation"],
  101. columns_order=["image", "annotation"],
  102. operations=[test_op])
  103. filename = "bounding_box_augment_crop_c_result.npz"
  104. save_and_check_md5(dataVoc2, filename, generate_golden=GENERATE_GOLDEN)
  105. unaugSamp, augSamp = [], []
  106. for unAug, Aug in zip(dataVoc1.create_dict_iterator(), dataVoc2.create_dict_iterator()):
  107. unaugSamp.append(unAug)
  108. augSamp.append(Aug)
  109. if plot_vis:
  110. visualize_with_bounding_boxes(unaugSamp, augSamp)
  111. # Restore config setting
  112. ds.config.set_seed(original_seed)
  113. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  114. def test_bounding_box_augment_valid_ratio_c(plot_vis=False):
  115. """
  116. Test BoundingBoxAugment op (testing with valid ratio, less than 1.
  117. Prints images side by side with and without Aug applied + bboxes to compare and test
  118. """
  119. logger.info("test_bounding_box_augment_valid_ratio_c")
  120. original_seed = config_get_set_seed(1)
  121. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  122. dataVoc1 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  123. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  124. test_op = c_vision.BoundingBoxAugment(c_vision.RandomHorizontalFlip(1), 0.9)
  125. # maps to fix annotations to minddata standard
  126. dataVoc1 = dataVoc1.map(input_columns=["annotation"],
  127. output_columns=["annotation"],
  128. operations=fix_annotate)
  129. dataVoc2 = dataVoc2.map(input_columns=["annotation"],
  130. output_columns=["annotation"],
  131. operations=fix_annotate)
  132. # map to apply ops
  133. dataVoc2 = dataVoc2.map(input_columns=["image", "annotation"],
  134. output_columns=["image", "annotation"],
  135. columns_order=["image", "annotation"],
  136. operations=[test_op]) # Add column for "annotation"
  137. filename = "bounding_box_augment_valid_ratio_c_result.npz"
  138. save_and_check_md5(dataVoc2, filename, generate_golden=GENERATE_GOLDEN)
  139. unaugSamp, augSamp = [], []
  140. for unAug, Aug in zip(dataVoc1.create_dict_iterator(), dataVoc2.create_dict_iterator()):
  141. unaugSamp.append(unAug)
  142. augSamp.append(Aug)
  143. if plot_vis:
  144. visualize_with_bounding_boxes(unaugSamp, augSamp)
  145. # Restore config setting
  146. ds.config.set_seed(original_seed)
  147. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  148. def test_bounding_box_augment_valid_edge_c(plot_vis=False):
  149. """
  150. Test BoundingBoxAugment op (testing with valid edge case, box covering full image).
  151. Prints images side by side with and without Aug applied + bboxes to compare and test
  152. """
  153. logger.info("test_bounding_box_augment_valid_edge_c")
  154. original_seed = config_get_set_seed(1)
  155. original_num_parallel_workers = config_get_set_num_parallel_workers(1)
  156. dataVoc1 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  157. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  158. test_op = c_vision.BoundingBoxAugment(c_vision.RandomHorizontalFlip(1), 1)
  159. # maps to fix annotations to minddata standard
  160. dataVoc1 = dataVoc1.map(input_columns=["annotation"],
  161. output_columns=["annotation"],
  162. operations=fix_annotate)
  163. dataVoc2 = dataVoc2.map(input_columns=["annotation"],
  164. output_columns=["annotation"],
  165. operations=fix_annotate)
  166. # map to apply ops
  167. # Add column for "annotation"
  168. dataVoc1 = dataVoc1.map(input_columns=["image", "annotation"],
  169. output_columns=["image", "annotation"],
  170. columns_order=["image", "annotation"],
  171. operations=lambda img, bbox:
  172. (img, np.array([[0, 0, img.shape[1], img.shape[0], 0, 0, 0]]).astype(np.uint32)))
  173. dataVoc2 = dataVoc2.map(input_columns=["image", "annotation"],
  174. output_columns=["image", "annotation"],
  175. columns_order=["image", "annotation"],
  176. operations=lambda img, bbox:
  177. (img, np.array([[0, 0, img.shape[1], img.shape[0], 0, 0, 0]]).astype(np.uint32)))
  178. dataVoc2 = dataVoc2.map(input_columns=["image", "annotation"],
  179. output_columns=["image", "annotation"],
  180. columns_order=["image", "annotation"],
  181. operations=[test_op])
  182. filename = "bounding_box_augment_valid_edge_c_result.npz"
  183. save_and_check_md5(dataVoc2, filename, generate_golden=GENERATE_GOLDEN)
  184. unaugSamp, augSamp = [], []
  185. for unAug, Aug in zip(dataVoc1.create_dict_iterator(), dataVoc2.create_dict_iterator()):
  186. unaugSamp.append(unAug)
  187. augSamp.append(Aug)
  188. if plot_vis:
  189. visualize_with_bounding_boxes(unaugSamp, augSamp)
  190. # Restore config setting
  191. ds.config.set_seed(original_seed)
  192. ds.config.set_num_parallel_workers(original_num_parallel_workers)
  193. def test_bounding_box_augment_invalid_ratio_c():
  194. """
  195. Test BoundingBoxAugment op with invalid input ratio
  196. """
  197. logger.info("test_bounding_box_augment_invalid_ratio_c")
  198. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  199. try:
  200. # ratio range is from 0 - 1
  201. test_op = c_vision.BoundingBoxAugment(c_vision.RandomHorizontalFlip(1), 1.5)
  202. # maps to fix annotations to minddata standard
  203. dataVoc2 = dataVoc2.map(input_columns=["annotation"],
  204. output_columns=["annotation"],
  205. operations=fix_annotate)
  206. # map to apply ops
  207. dataVoc2 = dataVoc2.map(input_columns=["image", "annotation"],
  208. output_columns=["image", "annotation"],
  209. columns_order=["image", "annotation"],
  210. operations=[test_op]) # Add column for "annotation"
  211. except ValueError as error:
  212. logger.info("Got an exception in DE: {}".format(str(error)))
  213. assert "Input is not" in str(error)
  214. def test_bounding_box_augment_invalid_bounds_c():
  215. """
  216. Test BoundingBoxAugment op with invalid bboxes.
  217. """
  218. logger.info("test_bounding_box_augment_invalid_bounds_c")
  219. test_op = c_vision.BoundingBoxAugment(c_vision.RandomHorizontalFlip(1),
  220. 1)
  221. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  222. check_bad_bbox(dataVoc2, test_op, InvalidBBoxType.WidthOverflow, "bounding boxes is out of bounds of the image")
  223. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  224. check_bad_bbox(dataVoc2, test_op, InvalidBBoxType.HeightOverflow, "bounding boxes is out of bounds of the image")
  225. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  226. check_bad_bbox(dataVoc2, test_op, InvalidBBoxType.NegativeXY, "min_x")
  227. dataVoc2 = ds.VOCDataset(DATA_DIR, task="Detection", mode="train", decode=True, shuffle=False)
  228. check_bad_bbox(dataVoc2, test_op, InvalidBBoxType.WrongShape, "4 features")
  229. if __name__ == "__main__":
  230. # set to false to not show plots
  231. test_bounding_box_augment_with_rotation_op(plot_vis=False)
  232. test_bounding_box_augment_with_crop_op(plot_vis=False)
  233. test_bounding_box_augment_valid_ratio_c(plot_vis=False)
  234. test_bounding_box_augment_valid_edge_c(plot_vis=False)
  235. test_bounding_box_augment_invalid_ratio_c()
  236. test_bounding_box_augment_invalid_bounds_c()