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 7.3 kB

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

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