-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjson2yolo.py
59 lines (47 loc) · 1.93 KB
/
json2yolo.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
import json
import os
from PIL import Image
from tqdm import tqdm
def process_annotations(json_file, images_folder, labels_folder):
# 读取JSON文件
with open(json_file, 'r') as file:
data = json.load(file)
annotations = data['annotations']
for annotation in tqdm(annotations):
category_id = annotation['category_id']
image_id = annotation['image_id']
# 获取图片尺寸
file_path = os.path.join(images_folder, str(image_id) + '.jpg')
try:
with Image.open(file_path) as img:
width, height = img.size
except FileNotFoundError:
continue
# 计算归一化的坐标
bbox = annotation['bbox']
x_center = (bbox[0] + bbox[2] / 2) / width
y_center = (bbox[1] + bbox[3] / 2) / height
w_norm = bbox[2] / width
h_norm = bbox[3] / height
# 写入标签文件,标签编号减1
label = category_id - 1
label_content = f"{label} {x_center} {y_center} {w_norm} {h_norm}"
label_file_path = os.path.join(labels_folder, str(image_id) + '.txt')
with open(label_file_path, 'a') as file:
file.write(label_content + '\n')
def create_labels_folder():
# 创建labels文件夹及其子文件夹
labels_folder = 'labels'
train_labels_folder = os.path.join(labels_folder, 'train')
val_labels_folder = os.path.join(labels_folder, 'val')
os.makedirs(train_labels_folder, exist_ok=True)
os.makedirs(val_labels_folder, exist_ok=True)
return train_labels_folder, val_labels_folder
def main():
train_labels_folder, val_labels_folder = create_labels_folder()
# 处理训练和验证数据
process_annotations('annotations/instances_train.json', 'images/train', train_labels_folder)
process_annotations('annotations/instances_val.json', 'images/val', val_labels_folder)
print("完成处理。")
if __name__ == "__main__":
main()