-
Notifications
You must be signed in to change notification settings - Fork 0
/
subcoco.py
132 lines (99 loc) · 3.8 KB
/
subcoco.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# -*- coding: utf-8 -*-
#
# This file is part of scraper.
# Copyright 2020 Leonardo Rossi <leonardo.rossi@studenti.unipr.it>.
#
# pysenslog is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# pysenslog is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pysenslog. If not, see <http://www.gnu.org/licenses/>.
"""Get a subset of COCO."""
import json
import argparse
import sys
from collections import defaultdict
def load_file(filename):
with open(filename, 'r') as file_:
data = json.load(file_)
return data
def save_file(filename, data):
with open(filename, 'w') as file_:
json.dump(data, file_)
def filter_categories(categories, annotations):
return [c for c in annotations['categories'] if c['id'] in categories]
def filter_annotations(categories, annotations):
return [a for a in annotations['annotations']
if a['category_id'] in categories]
def filter_images(image_ids, annotations):
return [i for i in annotations['images'] if i['id'] in image_ids]
def get_image_ids(annotations):
count_files = defaultdict(int)
for a in annotations['annotations']:
count_files[a['image_id']] = 1
return count_files.keys()
def count_categories_occurrence(annotations):
counter = defaultdict(int)
for a in annotations['annotations']:
counter[a['category_id']] += 1
return counter
def load_classes(filename):
file_ = open(filename)
return {k: v for (k, v) in enumerate(file_.read().split('\n'), 1)}
def cat_id2name(content):
cats = defaultdict(int)
for cat in content['categories']:
cats[cat['id']] = cat['name']
return cats
def print_stats(ann):
counter = count_categories_occurrence(ann)
classes = {}
if args.classes:
classes = load_classes(args.classes)
files = get_image_ids(ann)
cats = cat_id2name(ann)
print('Files: {0}'.format(len(files)))
for k in sorted(counter.keys()):
text = "Category {0}[{1}]: {2}".format(cats[k], k, counter[k])
if classes.get(k):
text = '{} -> {}'.format(text, classes.get(k))
print(text)
print('total: {0}'.format(sum(counter.values())))
def print_category_ids(ann):
cats = cat_id2name(ann)
print(' '.join([str(i) for i in sorted(cats.keys())]))
parser = argparse.ArgumentParser(description='COCO Subset')
parser.add_argument(
'--categories', '-c', nargs='+', type=int,
help='Extract annotations containing these categories')
parser.add_argument(
'--category_ids', '-i', action='store_true', default=False,
help='Extract the list of category ids')
parser.add_argument('--classes', '-l', help='File containing class names')
parser.add_argument(
'--stats', '-s', action='store_true', default=False,
help='Show only stats')
parser.add_argument('input_path', help='Input COCO annotation file')
parser.add_argument('--output_path', '-o', help='Output COCO annotation file')
args = parser.parse_args(sys.argv[1:])
# load all categories
ann = load_file(args.input_path)
if args.categories:
# filter by categories
ann['categories'] = filter_categories(args.categories, ann)
ann['annotations'] = filter_annotations(args.categories, ann)
ann['images'] = filter_images(get_image_ids(ann), ann)
if args.stats:
print_stats(ann)
sys.exit()
if args.category_ids:
print_category_ids(ann)
sys.exit()
save_file(args.output_path, ann)