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.

voc.py 6.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # ---------------------------------------------------------------------
  10. # Part of the following code in this file refs to torchvision
  11. # BSD 3-Clause License
  12. #
  13. # Copyright (c) Soumith Chintala 2016,
  14. # All rights reserved.
  15. # ---------------------------------------------------------------------
  16. import collections.abc
  17. import os
  18. import xml.etree.ElementTree as ET
  19. import cv2
  20. import numpy as np
  21. from .meta_vision import VisionDataset
  22. class PascalVOC(VisionDataset):
  23. r"""`Pascal VOC <http://host.robots.ox.ac.uk/pascal/VOC/>`_ Dataset.
  24. """
  25. supported_order = (
  26. "image",
  27. "boxes",
  28. "boxes_category",
  29. "mask",
  30. "info",
  31. )
  32. def __init__(self, root, image_set, *, order=None):
  33. if ("boxes" in order or "boxes_category" in order) and "mask" in order:
  34. raise ValueError("PascalVOC only supports boxes & boxes_category or mask, not both.")
  35. super().__init__(root, order=order, supported_order=self.supported_order)
  36. if not os.path.isdir(self.root):
  37. raise RuntimeError("Dataset not found or corrupted.")
  38. self.image_set = image_set
  39. image_dir = os.path.join(self.root, "JPEGImages")
  40. if "boxes" in order or "boxes_category" in order:
  41. annotation_dir = os.path.join(self.root, 'Annotations')
  42. splitdet_dir = os.path.join(self.root, "ImageSets/Main")
  43. split_f = os.path.join(splitdet_dir, image_set.rstrip("\n") + ".txt")
  44. with open(os.path.join(split_f), "r") as f:
  45. self.file_names = [x.strip() for x in f.readlines()]
  46. self.images = [os.path.join(image_dir, x + ".jpg") for x in self.file_names]
  47. self.annotations = [os.path.join(annotation_dir, x + ".xml") for x in self.file_names]
  48. assert len(self.images) == len(self.annotations)
  49. elif "mask" in order:
  50. if "aug" in image_set:
  51. mask_dir = os.path.join(self.root, "SegmentationClass_aug")
  52. else:
  53. mask_dir = os.path.join(self.root, "SegmentationClass")
  54. splitmask_dir = os.path.join(self.root, "ImageSets/Segmentation")
  55. split_f = os.path.join(splitmask_dir, image_set.rstrip("\n") + ".txt")
  56. with open(os.path.join(split_f), "r") as f:
  57. self.file_names = [x.strip() for x in f.readlines()]
  58. self.images = [os.path.join(image_dir, x + ".jpg") for x in self.file_names]
  59. self.masks = [os.path.join(mask_dir, x + ".png") for x in self.file_names]
  60. assert len(self.images) == len(self.masks)
  61. else:
  62. raise NotImplementedError
  63. def __getitem__(self, index):
  64. target = []
  65. for k in self.order:
  66. if k == "image":
  67. image = cv2.imread(self.images[index], cv2.IMREAD_COLOR)
  68. target.append(image)
  69. elif k == "boxes":
  70. anno = self.parse_voc_xml(ET.parse(self.annotations[index]).getroot())
  71. boxes = [obj["bndbox"] for obj in anno["annotation"]["object"]]
  72. # boxes type xyxy
  73. boxes = [(bb['xmin'], bb['ymin'], bb['xmax'], bb['ymax']) for bb in boxes]
  74. boxes = np.array(boxes, dtype=np.float32).reshape(-1, 4)
  75. target.append(boxes)
  76. elif k == "boxes_category":
  77. anno = self.parse_voc_xml(ET.parse(self.annotations[index]).getroot())
  78. boxes_category = [obj["name"] for obj in anno["annotation"]["object"]]
  79. boxes_category = [self.class_names.index(bc)-1 for bc in boxes_category]
  80. boxes_category = np.array(boxes_category, dtype=np.int32)
  81. target.append(boxes_category)
  82. elif k == "mask":
  83. if "aug" in self.image_set:
  84. mask = cv2.imread(self.masks[index], cv2.IMREAD_GRAYSCALE)
  85. else:
  86. mask = cv2.imread(self.masks[index], cv2.IMREAD_COLOR)
  87. mask = self._trans_mask(mask)
  88. mask = mask[:, :, np.newaxis]
  89. target.append(mask)
  90. elif k == "info":
  91. if image is None:
  92. image = cv2.imread(self.images[index], cv2.IMREAD_COLOR)
  93. info = [image.shape[0], image.shape[1], self.file_names[index]]
  94. target.append(info)
  95. else:
  96. raise NotImplementedError
  97. return tuple(target)
  98. def __len__(self):
  99. return len(self.images)
  100. def _trans_mask(self, mask):
  101. label = np.ones(mask.shape[:2]) * 255
  102. for i in range(len(self.class_colors)):
  103. b, g, r = self.class_colors[i]
  104. label[
  105. (mask[:, :, 0] == b) & (mask[:, :, 1] == g) & (mask[:, :, 2] == r)
  106. ] = i
  107. return label.astype(np.uint8)
  108. def parse_voc_xml(self, node):
  109. voc_dict = {}
  110. children = list(node)
  111. if children:
  112. def_dic = collections.defaultdict(list)
  113. for dc in map(self.parse_voc_xml, children):
  114. for ind, v in dc.items():
  115. def_dic[ind].append(v)
  116. if node.tag == "annotation":
  117. def_dic["object"] = [def_dic["object"]]
  118. voc_dict = {
  119. node.tag: {
  120. ind: v[0] if len(v) == 1 else v for ind, v in def_dic.items()
  121. }
  122. }
  123. if node.text:
  124. text = node.text.strip()
  125. if not children:
  126. voc_dict[node.tag] = text
  127. return voc_dict
  128. class_names = (
  129. "aeroplane",
  130. "bicycle",
  131. "bird",
  132. "boat",
  133. "bottle",
  134. "bus",
  135. "car",
  136. "cat",
  137. "chair",
  138. "cow",
  139. "diningtable",
  140. "dog",
  141. "horse",
  142. "motorbike",
  143. "person",
  144. "pottedplant",
  145. "sheep",
  146. "sofa",
  147. "train",
  148. "tvmonitor",
  149. )
  150. class_colors = [
  151. [0, 0, 128],
  152. [0, 128, 0],
  153. [0, 128, 128],
  154. [128, 0, 0],
  155. [128, 0, 128],
  156. [128, 128, 0],
  157. [128, 128, 128],
  158. [0, 0, 64],
  159. [0, 0, 192],
  160. [0, 128, 64],
  161. [0, 128, 192],
  162. [128, 0, 64],
  163. [128, 0, 192],
  164. [128, 128, 64],
  165. [128, 128, 192],
  166. [0, 64, 0],
  167. [0, 64, 128],
  168. [0, 192, 0],
  169. [0, 192, 128],
  170. [128, 64, 0],
  171. ]

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台