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

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

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