forked from RapidAI/LabelConvert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yolov5_yaml_2_coco.py
265 lines (217 loc) · 8.72 KB
/
yolov5_yaml_2_coco.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
import argparse
import glob
import json
import os
import shutil
import time
from pathlib import Path
import cv2
import yaml
from tqdm import tqdm
def read_txt(txt_path):
with open(str(txt_path), 'r', encoding='utf-8') as f:
data = list(map(lambda x: x.rstrip('\n'), f))
return data
def mkdir(dir_path):
Path(dir_path).mkdir(parents=True, exist_ok=True)
def verify_exists(file_path):
file_path = Path(file_path).resolve()
if not file_path.exists():
raise FileNotFoundError(f'The {file_path} is not exists!!!')
class YOLOV5CFG2COCO(object):
def __init__(self, yaml_path):
verify_exists(yaml_path)
with open(yaml_path, 'r', encoding="UTF-8") as f:
self.data_cfg = yaml.safe_load(f)
self.root_dir = Path(yaml_path).parent.parent
self.root_data_dir = Path(self.data_cfg.get('path'))
self.train_path = self._get_data_dir('train')
self.val_path = self._get_data_dir('val')
nc = self.data_cfg['nc']
if 'names' in self.data_cfg:
self.names = self.data_cfg.get('names')
else:
# assign class names if missing
self.names = [f'class{i}' for i in range(self.data_cfg['nc'])]
assert len(self.names) == nc, \
f'{len(self.names)} names found for nc={nc} dataset in {yaml_path}'
# 构建COCO格式目录
self.dst = self.root_dir / f"{Path(self.root_data_dir).stem}_COCO_format"
self.coco_train = "train2017"
self.coco_val = "val2017"
self.coco_annotation = "annotations"
self.coco_train_json = self.dst / self.coco_annotation / \
f'instances_{self.coco_train}.json'
self.coco_val_json = self.dst / self.coco_annotation / \
f'instances_{self.coco_val}.json'
mkdir(self.dst)
mkdir(self.dst / self.coco_train)
mkdir(self.dst / self.coco_val)
mkdir(self.dst / self.coco_annotation)
# 构建json内容结构
self.type = 'instances'
self.categories = []
self._get_category()
self.annotation_id = 1
cur_year = time.strftime('%Y', time.localtime(time.time()))
self.info = {
'year': int(cur_year),
'version': '1.0',
'description': 'For object detection',
'date_created': cur_year,
}
self.licenses = [{
'id': 1,
'name': 'Apache License v2.0',
'url': 'https://github.com/RapidAI/YOLO2COCO/LICENSE',
}]
def _get_data_dir(self, mode):
data_dir = self.data_cfg.get(mode)
if data_dir:
if isinstance(data_dir, str):
full_path = [str(self.root_data_dir / data_dir)]
elif isinstance(data_dir, list):
full_path = [str(self.root_data_dir / one_dir)
for one_dir in data_dir]
else:
raise TypeError(f'{data_dir} is not str or list.')
else:
raise ValueError(f'{mode} dir is not in the yaml.')
return full_path
def _get_category(self):
for i, category in enumerate(self.names, start=1):
self.categories.append({
'supercategory': category,
'id': i,
'name': category,
})
def generate(self):
self.train_files = self.get_files(self.train_path)
self.valid_files = self.get_files(self.val_path)
train_dest_dir = Path(self.dst) / self.coco_train
self.gen_dataset(self.train_files, train_dest_dir,
self.coco_train_json, mode='train')
val_dest_dir = Path(self.dst) / self.coco_val
self.gen_dataset(self.valid_files, val_dest_dir,
self.coco_val_json, mode='val')
print(f"The output directory is: {str(self.dst)}")
def get_files(self, path):
# include image suffixes
IMG_FORMATS = ['bmp', 'dng', 'jpeg', 'jpg',
'mpo', 'png', 'tif', 'tiff', 'webp']
f = []
for p in path:
p = Path(p) # os-agnostic
if p.is_dir(): # dir
f += glob.glob(str(p / '**' / '*.*'), recursive=True)
# f = list(p.rglob('*.*')) # pathlib
elif p.is_file(): # file
with open(p) as t:
t = t.read().strip().splitlines()
parent = str(p.parent) + os.sep
# local to global path
f += [x.replace('./', parent)
if x.startswith('./') else x for x in t]
# f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
else:
raise Exception(f'{p} does not exist')
im_files = sorted(x.replace('/', os.sep)
for x in f if x.split('.')[-1].lower() in IMG_FORMATS)
return im_files
def gen_dataset(self, img_paths, target_img_path, target_json, mode):
"""
https://cocodataset.org/#format-data
"""
images = []
annotations = []
sa, sb = os.sep + 'images' + os.sep, os.sep + \
'labels' + os.sep # /images/, /labels/ substrings
for img_id, img_path in enumerate(tqdm(img_paths, desc=mode), 1):
label_path = sb.join(img_path.rsplit(
sa, 1)).rsplit('.', 1)[0] + '.txt'
img_path = Path(img_path)
verify_exists(img_path)
imgsrc = cv2.imread(str(img_path))
height, width = imgsrc.shape[:2]
dest_file_name = f'{img_id:012d}.jpg'
save_img_path = target_img_path / dest_file_name
if img_path.suffix.lower() == ".jpg":
shutil.copyfile(img_path, save_img_path)
else:
cv2.imwrite(str(save_img_path), imgsrc)
images.append({
'date_captured': '2021',
'file_name': dest_file_name,
'id': img_id,
'height': height,
'width': width,
})
if Path(label_path).exists():
new_anno = self.read_annotation(label_path, img_id,
height, width)
if len(new_anno) > 0:
annotations.extend(new_anno)
else:
# print(f'{label_path} is empty')
raise ValueError(f'{label_path} is empty')
else:
raise FileNotFoundError(f'{label_path} not exists')
json_data = {
'info': self.info,
'images': images,
'licenses': self.licenses,
'type': self.type,
'annotations': annotations,
'categories': self.categories,
}
with open(target_json, 'w', encoding='utf-8') as f:
json.dump(json_data, f, ensure_ascii=False)
def read_annotation(self, txt_file, img_id, height, width):
annotation = []
all_info = read_txt(txt_file)
for label_info in all_info:
# 遍历一张图中不同标注对象
label_info = label_info.split(" ")
if len(label_info) < 5:
continue
category_id, vertex_info = label_info[0], label_info[1:]
segmentation, bbox, area = self._get_annotation(vertex_info,
height, width)
annotation.append({
'segmentation': segmentation,
'area': area,
'iscrowd': 0,
'image_id': img_id,
'bbox': bbox,
'category_id': int(category_id)+1,
'id': self.annotation_id,
})
self.annotation_id += 1
return annotation
@staticmethod
def _get_annotation(vertex_info, height, width):
cx, cy, w, h = [float(i) for i in vertex_info]
cx = cx * width
cy = cy * height
box_w = w * width
box_h = h * height
# left top
x0 = max(cx - box_w / 2, 0)
y0 = max(cy - box_h / 2, 0)
# right bottomt
x1 = min(x0 + box_w, width)
y1 = min(y0 + box_h, height)
segmentation = [[x0, y0, x1, y0, x1, y1, x0, y1]]
bbox = [x0, y0, box_w, box_h]
area = box_w * box_h
return segmentation, bbox, area
if __name__ == "__main__":
parser = argparse.ArgumentParser('Datasets converter from YOLOV5 to COCO')
parser.add_argument('--yaml_path', type=str,
default='dataset/YOLOV5_yaml/sample.yaml',
help='Dataset cfg file')
args = parser.parse_args()
converter = YOLOV5CFG2COCO(args.yaml_path)
converter.generate()