Doraemon-AI commited on
Commit
41af6a6
1 Parent(s): 293fc85
Files changed (2) hide show
  1. labelme2coco.py +187 -0
  2. labels.txt +12 -0
labelme2coco.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import argparse
4
+ import collections
5
+ import datetime
6
+ import glob
7
+ import json
8
+ import os
9
+ import os.path as osp
10
+ import sys
11
+ import uuid
12
+
13
+ import imgviz
14
+ import numpy as np
15
+
16
+ import labelme
17
+
18
+ try:
19
+ import pycocotools.mask
20
+ except ImportError:
21
+ print("Please install pycocotools:\n\n pip install pycocotools\n")
22
+ sys.exit(1)
23
+
24
+
25
+ def main():
26
+ parser = argparse.ArgumentParser(
27
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter
28
+ )
29
+ parser.add_argument("input_dir", help="input annotated directory")
30
+ parser.add_argument("output_dir", help="output dataset directory")
31
+ parser.add_argument("--labels", help="labels file", required=True)
32
+ parser.add_argument(
33
+ "--noviz", help="no visualization", action="store_true"
34
+ )
35
+ args = parser.parse_args()
36
+
37
+ if osp.exists(args.output_dir):
38
+ print("Output directory already exists:", args.output_dir)
39
+ sys.exit(1)
40
+ os.makedirs(args.output_dir)
41
+ os.makedirs(osp.join(args.output_dir, "JPEGImages"))
42
+ if not args.noviz:
43
+ os.makedirs(osp.join(args.output_dir, "Visualization"))
44
+ print("Creating dataset:", args.output_dir)
45
+
46
+ now = datetime.datetime.now()
47
+
48
+ data = dict(
49
+ info=dict(
50
+ description=None,
51
+ url=None,
52
+ version=None,
53
+ year=now.year,
54
+ contributor=None,
55
+ date_created=now.strftime("%Y-%m-%d %H:%M:%S.%f"),
56
+ ),
57
+ licenses=[dict(url=None, id=0, name=None,)],
58
+ images=[
59
+ # license, url, file_name, height, width, date_captured, id
60
+ ],
61
+ type="instances",
62
+ annotations=[
63
+ # segmentation, area, iscrowd, image_id, bbox, category_id, id
64
+ ],
65
+ categories=[
66
+ # supercategory, id, name
67
+ ],
68
+ )
69
+
70
+ class_name_to_id = {}
71
+ for i, line in enumerate(open(args.labels).readlines()):
72
+ class_id = i - 1 # starts with -1
73
+ class_name = line.strip()
74
+ if class_id == -1:
75
+ assert class_name == "__ignore__"
76
+ continue
77
+ class_name_to_id[class_name] = class_id
78
+ data["categories"].append(
79
+ dict(supercategory=None, id=class_id, name=class_name,)
80
+ )
81
+
82
+ out_ann_file = osp.join(args.output_dir, "annotations.json")
83
+ label_files = glob.glob(osp.join(args.input_dir, "*.json"))
84
+ for image_id, filename in enumerate(label_files):
85
+ print("Generating dataset from:", filename)
86
+
87
+ label_file = labelme.LabelFile(filename=filename)
88
+
89
+ base = osp.splitext(osp.basename(filename))[0]
90
+ out_img_file = osp.join(args.output_dir, "JPEGImages", base + ".jpg")
91
+
92
+ img = labelme.utils.img_data_to_arr(label_file.imageData)
93
+ imgviz.io.imsave(out_img_file, img)
94
+ data["images"].append(
95
+ dict(
96
+ license=0,
97
+ url=None,
98
+ file_name=osp.relpath(out_img_file, osp.dirname(out_ann_file)),
99
+ height=img.shape[0],
100
+ width=img.shape[1],
101
+ date_captured=None,
102
+ id=image_id,
103
+ )
104
+ )
105
+
106
+ masks = {} # for area
107
+ segmentations = collections.defaultdict(list) # for segmentation
108
+ for shape in label_file.shapes:
109
+ points = shape["points"]
110
+ label = shape["label"]
111
+ group_id = shape.get("group_id")
112
+ shape_type = shape.get("shape_type", "polygon")
113
+ mask = labelme.utils.shape_to_mask(
114
+ img.shape[:2], points, shape_type
115
+ )
116
+
117
+ if group_id is None:
118
+ group_id = uuid.uuid1()
119
+
120
+ instance = (label, group_id)
121
+
122
+ if instance in masks:
123
+ masks[instance] = masks[instance] | mask
124
+ else:
125
+ masks[instance] = mask
126
+
127
+ if shape_type == "rectangle":
128
+ (x1, y1), (x2, y2) = points
129
+ x1, x2 = sorted([x1, x2])
130
+ y1, y2 = sorted([y1, y2])
131
+ points = [x1, y1, x2, y1, x2, y2, x1, y2]
132
+ else:
133
+ points = np.asarray(points).flatten().tolist()
134
+
135
+ segmentations[instance].append(points)
136
+ segmentations = dict(segmentations)
137
+
138
+ for instance, mask in masks.items():
139
+ cls_name, group_id = instance
140
+ if cls_name not in class_name_to_id:
141
+ continue
142
+ cls_id = class_name_to_id[cls_name]
143
+
144
+ mask = np.asfortranarray(mask.astype(np.uint8))
145
+ mask = pycocotools.mask.encode(mask)
146
+ area = float(pycocotools.mask.area(mask))
147
+ bbox = pycocotools.mask.toBbox(mask).flatten().tolist()
148
+
149
+ data["annotations"].append(
150
+ dict(
151
+ id=len(data["annotations"]),
152
+ image_id=image_id,
153
+ category_id=cls_id,
154
+ segmentation=segmentations[instance],
155
+ area=area,
156
+ bbox=bbox,
157
+ iscrowd=0,
158
+ )
159
+ )
160
+
161
+ if not args.noviz:
162
+ labels, captions, masks = zip(
163
+ *[
164
+ (class_name_to_id[cnm], cnm, msk)
165
+ for (cnm, gid), msk in masks.items()
166
+ if cnm in class_name_to_id
167
+ ]
168
+ )
169
+ viz = imgviz.instances2rgb(
170
+ image=img,
171
+ labels=labels,
172
+ masks=masks,
173
+ captions=captions,
174
+ font_size=15,
175
+ line_width=2,
176
+ )
177
+ out_viz_file = osp.join(
178
+ args.output_dir, "Visualization", base + ".jpg"
179
+ )
180
+ imgviz.io.imsave(out_viz_file, viz)
181
+
182
+ with open(out_ann_file, "w") as f:
183
+ json.dump(data, f)
184
+
185
+
186
+ if __name__ == "__main__":
187
+ main()
labels.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __ignore__
2
+ _background_
3
+ Text
4
+ Title
5
+ Figure
6
+ Figure caption
7
+ Table
8
+ Table caption
9
+ Header
10
+ Footer
11
+ Reference
12
+ Equation