-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlabels2yoloFormat.py
More file actions
41 lines (29 loc) · 1.67 KB
/
labels2yoloFormat.py
File metadata and controls
41 lines (29 loc) · 1.67 KB
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
import os
import cv2
def main():
read_label_dir = 'D:/study/python/OpenCV_Labeling/labels'
read_image_dir = 'D:/study/python/OpenCV_Labeling/images'
write_label_dir = 'D:/study/python/OpenCV_Labeling/labels_formal'
for label_folder_idx, label_folder in enumerate(os.listdir(read_label_dir)):
for file_name in os.listdir(read_label_dir + '/' + label_folder):
file_name = file_name.split('.txt')[0]
read_label_file = open(read_label_dir + '/' + label_folder + '/' + file_name + '.txt', 'r')
read_image_file = cv2.imread(read_image_dir + '/' + label_folder + '/' + file_name + '.jpg')
if not os.path.exists(write_label_dir + '/' + label_folder):
os.makedirs(write_label_dir + '/' + label_folder)
write_label_file = open(write_label_dir + '/' + label_folder + '/' + file_name + '.txt', 'w')
img_width = read_image_file.shape[1]
img_height = read_image_file.shape[0]
for line_idx, line in enumerate(read_label_file.readlines()):
if line_idx == 0:
continue
x = int(line.split(' ')[1]) / img_width
y = int(line.split(' ')[2]) / img_height
w = (int(line.split(' ')[3]) - int(line.split(' ')[1])) / img_width
h = (int(line.split(' ')[4]) - int(line.split(' ')[2])) / img_height
write_label_file.write('%s %f %f %f %f' % (label_folder, x + w/2, y + h/2, w, h))
read_label_file.close()
write_label_file.close()
print('Done:', write_label_dir + '/' + label_folder + '/' + file_name)
if __name__ == "__main__":
main()