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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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(
  35. "PascalVOC only supports boxes & boxes_category or mask, not both."
  36. )
  37. super().__init__(root, order=order, supported_order=self.supported_order)
  38. if not os.path.isdir(self.root):
  39. raise RuntimeError("Dataset not found or corrupted.")
  40. self.image_set = image_set
  41. image_dir = os.path.join(self.root, "JPEGImages")
  42. if "boxes" in order or "boxes_category" in order:
  43. annotation_dir = os.path.join(self.root, "Annotations")
  44. splitdet_dir = os.path.join(self.root, "ImageSets/Main")
  45. split_f = os.path.join(splitdet_dir, image_set.rstrip("\n") + ".txt")
  46. with open(os.path.join(split_f), "r") as f:
  47. self.file_names = [x.strip() for x in f.readlines()]
  48. self.images = [os.path.join(image_dir, x + ".jpg") for x in self.file_names]
  49. self.annotations = [
  50. os.path.join(annotation_dir, x + ".xml") for x in self.file_names
  51. ]
  52. assert len(self.images) == len(self.annotations)
  53. elif "mask" in order:
  54. if "aug" in image_set:
  55. mask_dir = os.path.join(self.root, "SegmentationClass_aug")
  56. else:
  57. mask_dir = os.path.join(self.root, "SegmentationClass")
  58. splitmask_dir = os.path.join(self.root, "ImageSets/Segmentation")
  59. split_f = os.path.join(splitmask_dir, image_set.rstrip("\n") + ".txt")
  60. with open(os.path.join(split_f), "r") as f:
  61. self.file_names = [x.strip() for x in f.readlines()]
  62. self.images = [os.path.join(image_dir, x + ".jpg") for x in self.file_names]
  63. self.masks = [os.path.join(mask_dir, x + ".png") for x in self.file_names]
  64. assert len(self.images) == len(self.masks)
  65. else:
  66. raise NotImplementedError
  67. self.img_infos = dict()
  68. def __getitem__(self, index):
  69. target = []
  70. for k in self.order:
  71. if k == "image":
  72. image = cv2.imread(self.images[index], cv2.IMREAD_COLOR)
  73. target.append(image)
  74. elif k == "boxes":
  75. anno = self.parse_voc_xml(ET.parse(self.annotations[index]).getroot())
  76. boxes = [obj["bndbox"] for obj in anno["annotation"]["object"]]
  77. # boxes type xyxy
  78. boxes = [
  79. (bb["xmin"], bb["ymin"], bb["xmax"], bb["ymax"]) for bb in boxes
  80. ]
  81. boxes = np.array(boxes, dtype=np.float32).reshape(-1, 4)
  82. target.append(boxes)
  83. elif k == "boxes_category":
  84. anno = self.parse_voc_xml(ET.parse(self.annotations[index]).getroot())
  85. boxes_category = [obj["name"] for obj in anno["annotation"]["object"]]
  86. boxes_category = [
  87. self.class_names.index(bc) + 1 for bc in boxes_category
  88. ]
  89. boxes_category = np.array(boxes_category, dtype=np.int32)
  90. target.append(boxes_category)
  91. elif k == "mask":
  92. if "aug" in self.image_set:
  93. mask = cv2.imread(self.masks[index], cv2.IMREAD_GRAYSCALE)
  94. else:
  95. mask = cv2.imread(self.masks[index], cv2.IMREAD_COLOR)
  96. mask = self._trans_mask(mask)
  97. mask = mask[:, :, np.newaxis]
  98. target.append(mask)
  99. elif k == "info":
  100. info = self.get_img_info(index, image)
  101. info = [info["height"], info["width"], info["file_name"]]
  102. target.append(info)
  103. else:
  104. raise NotImplementedError
  105. return tuple(target)
  106. def __len__(self):
  107. return len(self.images)
  108. def get_img_info(self, index, image=None):
  109. if index not in self.img_infos:
  110. if image is None:
  111. image = cv2.imread(self.images[index], cv2.IMREAD_COLOR)
  112. self.img_infos[index] = dict(
  113. height=image.shape[0],
  114. width=image.shape[1],
  115. file_name=self.file_names[index],
  116. )
  117. return self.img_infos[index]
  118. def _trans_mask(self, mask):
  119. label = np.ones(mask.shape[:2]) * 255
  120. for i in range(len(self.class_colors)):
  121. b, g, r = self.class_colors[i]
  122. label[
  123. (mask[:, :, 0] == b) & (mask[:, :, 1] == g) & (mask[:, :, 2] == r)
  124. ] = i
  125. return label.astype(np.uint8)
  126. def parse_voc_xml(self, node):
  127. voc_dict = {}
  128. children = list(node)
  129. if children:
  130. def_dic = collections.defaultdict(list)
  131. for dc in map(self.parse_voc_xml, children):
  132. for ind, v in dc.items():
  133. def_dic[ind].append(v)
  134. if node.tag == "annotation":
  135. def_dic["object"] = [def_dic["object"]]
  136. voc_dict = {
  137. node.tag: {
  138. ind: v[0] if len(v) == 1 else v for ind, v in def_dic.items()
  139. }
  140. }
  141. if node.text:
  142. text = node.text.strip()
  143. if not children:
  144. voc_dict[node.tag] = text
  145. return voc_dict
  146. class_names = (
  147. "aeroplane",
  148. "bicycle",
  149. "bird",
  150. "boat",
  151. "bottle",
  152. "bus",
  153. "car",
  154. "cat",
  155. "chair",
  156. "cow",
  157. "diningtable",
  158. "dog",
  159. "horse",
  160. "motorbike",
  161. "person",
  162. "pottedplant",
  163. "sheep",
  164. "sofa",
  165. "train",
  166. "tvmonitor",
  167. )

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