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.

pascal_voc.py 7.8 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import os.path as osp
  4. import xml.etree.ElementTree as ET
  5. import mmcv
  6. import numpy as np
  7. from mmdet.core import voc_classes
  8. label_ids = {name: i for i, name in enumerate(voc_classes())}
  9. def parse_xml(args):
  10. xml_path, img_path = args
  11. tree = ET.parse(xml_path)
  12. root = tree.getroot()
  13. size = root.find('size')
  14. w = int(size.find('width').text)
  15. h = int(size.find('height').text)
  16. bboxes = []
  17. labels = []
  18. bboxes_ignore = []
  19. labels_ignore = []
  20. for obj in root.findall('object'):
  21. name = obj.find('name').text
  22. label = label_ids[name]
  23. difficult = int(obj.find('difficult').text)
  24. bnd_box = obj.find('bndbox')
  25. bbox = [
  26. int(bnd_box.find('xmin').text),
  27. int(bnd_box.find('ymin').text),
  28. int(bnd_box.find('xmax').text),
  29. int(bnd_box.find('ymax').text)
  30. ]
  31. if difficult:
  32. bboxes_ignore.append(bbox)
  33. labels_ignore.append(label)
  34. else:
  35. bboxes.append(bbox)
  36. labels.append(label)
  37. if not bboxes:
  38. bboxes = np.zeros((0, 4))
  39. labels = np.zeros((0, ))
  40. else:
  41. bboxes = np.array(bboxes, ndmin=2) - 1
  42. labels = np.array(labels)
  43. if not bboxes_ignore:
  44. bboxes_ignore = np.zeros((0, 4))
  45. labels_ignore = np.zeros((0, ))
  46. else:
  47. bboxes_ignore = np.array(bboxes_ignore, ndmin=2) - 1
  48. labels_ignore = np.array(labels_ignore)
  49. annotation = {
  50. 'filename': img_path,
  51. 'width': w,
  52. 'height': h,
  53. 'ann': {
  54. 'bboxes': bboxes.astype(np.float32),
  55. 'labels': labels.astype(np.int64),
  56. 'bboxes_ignore': bboxes_ignore.astype(np.float32),
  57. 'labels_ignore': labels_ignore.astype(np.int64)
  58. }
  59. }
  60. return annotation
  61. def cvt_annotations(devkit_path, years, split, out_file):
  62. if not isinstance(years, list):
  63. years = [years]
  64. annotations = []
  65. for year in years:
  66. filelist = osp.join(devkit_path,
  67. f'VOC{year}/ImageSets/Main/{split}.txt')
  68. if not osp.isfile(filelist):
  69. print(f'filelist does not exist: {filelist}, '
  70. f'skip voc{year} {split}')
  71. return
  72. img_names = mmcv.list_from_file(filelist)
  73. xml_paths = [
  74. osp.join(devkit_path, f'VOC{year}/Annotations/{img_name}.xml')
  75. for img_name in img_names
  76. ]
  77. img_paths = [
  78. f'VOC{year}/JPEGImages/{img_name}.jpg' for img_name in img_names
  79. ]
  80. part_annotations = mmcv.track_progress(parse_xml,
  81. list(zip(xml_paths, img_paths)))
  82. annotations.extend(part_annotations)
  83. if out_file.endswith('json'):
  84. annotations = cvt_to_coco_json(annotations)
  85. mmcv.dump(annotations, out_file)
  86. return annotations
  87. def cvt_to_coco_json(annotations):
  88. image_id = 0
  89. annotation_id = 0
  90. coco = dict()
  91. coco['images'] = []
  92. coco['type'] = 'instance'
  93. coco['categories'] = []
  94. coco['annotations'] = []
  95. image_set = set()
  96. def addAnnItem(annotation_id, image_id, category_id, bbox, difficult_flag):
  97. annotation_item = dict()
  98. annotation_item['segmentation'] = []
  99. seg = []
  100. # bbox[] is x1,y1,x2,y2
  101. # left_top
  102. seg.append(int(bbox[0]))
  103. seg.append(int(bbox[1]))
  104. # left_bottom
  105. seg.append(int(bbox[0]))
  106. seg.append(int(bbox[3]))
  107. # right_bottom
  108. seg.append(int(bbox[2]))
  109. seg.append(int(bbox[3]))
  110. # right_top
  111. seg.append(int(bbox[2]))
  112. seg.append(int(bbox[1]))
  113. annotation_item['segmentation'].append(seg)
  114. xywh = np.array(
  115. [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]])
  116. annotation_item['area'] = int(xywh[2] * xywh[3])
  117. if difficult_flag == 1:
  118. annotation_item['ignore'] = 0
  119. annotation_item['iscrowd'] = 1
  120. else:
  121. annotation_item['ignore'] = 0
  122. annotation_item['iscrowd'] = 0
  123. annotation_item['image_id'] = int(image_id)
  124. annotation_item['bbox'] = xywh.astype(int).tolist()
  125. annotation_item['category_id'] = int(category_id)
  126. annotation_item['id'] = int(annotation_id)
  127. coco['annotations'].append(annotation_item)
  128. return annotation_id + 1
  129. for category_id, name in enumerate(voc_classes()):
  130. category_item = dict()
  131. category_item['supercategory'] = str('none')
  132. category_item['id'] = int(category_id)
  133. category_item['name'] = str(name)
  134. coco['categories'].append(category_item)
  135. for ann_dict in annotations:
  136. file_name = ann_dict['filename']
  137. ann = ann_dict['ann']
  138. assert file_name not in image_set
  139. image_item = dict()
  140. image_item['id'] = int(image_id)
  141. image_item['file_name'] = str(file_name)
  142. image_item['height'] = int(ann_dict['height'])
  143. image_item['width'] = int(ann_dict['width'])
  144. coco['images'].append(image_item)
  145. image_set.add(file_name)
  146. bboxes = ann['bboxes'][:, :4]
  147. labels = ann['labels']
  148. for bbox_id in range(len(bboxes)):
  149. bbox = bboxes[bbox_id]
  150. label = labels[bbox_id]
  151. annotation_id = addAnnItem(
  152. annotation_id, image_id, label, bbox, difficult_flag=0)
  153. bboxes_ignore = ann['bboxes_ignore'][:, :4]
  154. labels_ignore = ann['labels_ignore']
  155. for bbox_id in range(len(bboxes_ignore)):
  156. bbox = bboxes_ignore[bbox_id]
  157. label = labels_ignore[bbox_id]
  158. annotation_id = addAnnItem(
  159. annotation_id, image_id, label, bbox, difficult_flag=1)
  160. image_id += 1
  161. return coco
  162. def parse_args():
  163. parser = argparse.ArgumentParser(
  164. description='Convert PASCAL VOC annotations to mmdetection format')
  165. parser.add_argument('devkit_path', help='pascal voc devkit path')
  166. parser.add_argument('-o', '--out-dir', help='output path')
  167. parser.add_argument(
  168. '--out-format',
  169. default='pkl',
  170. choices=('pkl', 'coco'),
  171. help='output format, "coco" indicates coco annotation format')
  172. args = parser.parse_args()
  173. return args
  174. def main():
  175. args = parse_args()
  176. devkit_path = args.devkit_path
  177. out_dir = args.out_dir if args.out_dir else devkit_path
  178. mmcv.mkdir_or_exist(out_dir)
  179. years = []
  180. if osp.isdir(osp.join(devkit_path, 'VOC2007')):
  181. years.append('2007')
  182. if osp.isdir(osp.join(devkit_path, 'VOC2012')):
  183. years.append('2012')
  184. if '2007' in years and '2012' in years:
  185. years.append(['2007', '2012'])
  186. if not years:
  187. raise IOError(f'The devkit path {devkit_path} contains neither '
  188. '"VOC2007" nor "VOC2012" subfolder')
  189. out_fmt = f'.{args.out_format}'
  190. if args.out_format == 'coco':
  191. out_fmt = '.json'
  192. for year in years:
  193. if year == '2007':
  194. prefix = 'voc07'
  195. elif year == '2012':
  196. prefix = 'voc12'
  197. elif year == ['2007', '2012']:
  198. prefix = 'voc0712'
  199. for split in ['train', 'val', 'trainval']:
  200. dataset_name = prefix + '_' + split
  201. print(f'processing {dataset_name} ...')
  202. cvt_annotations(devkit_path, year, split,
  203. osp.join(out_dir, dataset_name + out_fmt))
  204. if not isinstance(year, list):
  205. dataset_name = prefix + '_test'
  206. print(f'processing {dataset_name} ...')
  207. cvt_annotations(devkit_path, year, 'test',
  208. osp.join(out_dir, dataset_name + out_fmt))
  209. print('Done!')
  210. if __name__ == '__main__':
  211. main()

No Description

Contributors (2)