-
Notifications
You must be signed in to change notification settings - Fork 1
/
02_coco2yolo_label.py
executable file
·83 lines (64 loc) · 2.54 KB
/
02_coco2yolo_label.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
'''
Description:
Date: 2022-06-26 09:11:33
LastEditTime: 2022-09-05 09:17:30
FilePath: /10_coco_label_tool/02_voc2yolo_label.py
'''
import os
import json
from tqdm import tqdm
import argparse
def convert(size, box):
'''
size: 图片的宽和高(w,h)
box格式: x,y,w,h
返回值:x_center/image_width y_center/image_height width/image_width height/image_height
'''
dw = 1. / (size[0])
dh = 1. / (size[1])
x = box[0] + box[2] / 2.0
y = box[1] + box[3] / 2.0
w = box[2]
h = box[3]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
'''
RUN:
python 02_coco2yolo_label.py --json_file _annotations.coco.json --save_dir labels
'''
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--json_file', default='/home/rane/2TDisk/01_Projects/04_huagong_proj/Dataset_Dumei/0822-ip121_2_3+0/02_0825_ip12_0123_data/all_coco/annotations/instances_train2017.json', type=str, help="coco file path")
parser.add_argument('--save_dir', default='/home/rane/2TDisk/01_Projects/04_huagong_proj/Dataset_Dumei/0822-ip121_2_3+0/02_0825_ip12_0123_data/all_yolo/labels', type=str, help="where to save .txt labels")
arg = parser.parse_args()
data = json.load(open(arg.json_file, 'r'))
# 如果存放txt文件夹不存在,则创建
if not os.path.exists(arg.save_dir):
os.makedirs(arg.save_dir)
id_map = {}
# 解析目标类别,也就是 categories 字段,并将类别写入文件 classes.txt 中
with open(os.path.join(arg.save_dir, 'classes.txt'), 'w') as f:
for i, category in enumerate(data['categories']):
f.write(f"{category['name']}\n")
id_map[category['id']] = i
for img in tqdm(data['images']):
# 解析 images 字段,分别取出图片文件名、图片的宽和高、图片id
filename = img["file_name"]
img_width = img["width"]
img_height = img["height"]
img_id = img["id"]
head, tail = os.path.splitext(filename)
# txt文件名,与对应图片名只有后缀名不一样
txt_name = head + ".txt"
f_txt = open(os.path.join(arg.save_dir, txt_name), 'w')
for ann in data['annotations']:
if ann['image_id'] == img_id:
box = convert((img_width, img_height), ann["bbox"])
# 写入txt,共5个字段
f_txt.write("%s %s %s %s %s\n" % (
id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
f_txt.close()
print("finish!")