-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_to_txt.py
41 lines (35 loc) · 1.33 KB
/
json_to_txt.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
# author: roczhang
# file: json_to_txt.py
# time: 2021/05/11
import json
import os
# 将json文件夹转换成txt(yolo格式)
json_dir = 'F:/YOLO/change_rice_label/test/'
json_files = os.listdir(json_dir)
txt_dir = 'F:/YOLO/change_rice_label/txt_test'
if not os.path.exists(txt_dir):
os.makedirs(txt_dir)
for json_file in json_files:
if json_file.split('.')[1] == 'jpg':
continue
# json_file = '1.json'
txt_name = json_file.split('.')[0] + '.txt'
# print(txt_name)
txt_file = open(os.path.join(txt_dir, txt_name), 'w')
def convert(x1, y1, x2, y2):
x = ((x1 + x2) / 2) / 1920
y = ((y1 + y2) / 2) / 1080
width = abs((x1 - x2) / 1920)
high = abs((y1 - y2) / 1080)
return x, y, width, high
with open(json_dir + json_file, 'r', encoding='utf-8') as json_:
json_ = json.load(json_)
for shape in json_['shapes']:
x1, y1 = shape['points'][0]
x2, y2 = shape['points'][1]
# minc, minr = [float(temp) for temp in shape['points'][0]]
# maxc, maxr = [float(temp) for temp in shape['points'][1]]
x, y, width, high = convert(x1, y1, x2, y2)
txt_file.write("0 {} {} {} {}\n".format(x, y, width, high))
print("finished convert json to txt! file name {}".format(json_file))
txt_file.close()