##wider face label to yolo label
'''
# wider_face_train_bbx_gt.txt的文件内容
# 第一行为名字
# 第二行为头像的数量 n
# 剩下的为n行人脸数据,前4位为x1,y1,w,h;后六位为官网封面上六个参数{scal, pose, oclussion, expression, makeup, illumination}
# 以下为示例
# 0--Parade/0_Parade_marchingband_1_117.jpg
# 9
# 69 359 50 36 1 0 0 0 0 1
# 227 382 56 43 1 0 1 0 0 1
# 296 305 44 26 1 0 0 0 0 1
# 353 280 40 36 2 0 0 0 2 1
# 885 377 63 41 1 0 0 0 0 1
# 819 391 34 43 2 0 0 0 1 0
# 727 342 37 31 2 0 0 0 0 1
# 598 246 33 29 2 0 0 0 0 1
# 740 308 45 33 1 0 0 0 2 1
# 0--Parade/0_Parade_Parade_0_194.jpg
# 5
# 111 425 122 127 0 1 0 0 0 1
# 209 347 70 103 0 1 0 0 0 0
# 368 252 89 133 0 1 0 0 0 0
# 555 282 89 100 0 1 0 0 0 1
# 707 252 92 133 0 1 0 0 0 0
'''
import os
import torch
import cv2
im_folder = 'xxxxx'
gtfile = 'xxxx/wider_face_train(val)_bbx_gt.txt'
label_folder = 'xxxxx'
def H_W(image):
f = cv2.imread(image)
return f.shape
def convert2yolo(box):
claid = 0
dw = 1./W
dh = 1./H
cen_x = box[0] + box[2]/2.0
cen_y = box[1] + box[3]/2.0
w = box[2] * dw
h = box[3] * dh
cen_x = cen_x * dw
cen_y = cen_y * dh
return (claid,cen_x,cen_y,w,h)
with open(gtfile, "r") as gt:
while(True):
gt_con = gt.readline()[:-1]
if gt_con is None or gt_con == "":
break
gt_con_stem = gt_con.split('.')[0]
txt_path = label_folder + gt_con_stem + '.txt'
file_dir_first = gt_con.split('/')[0]
# os.mkdir(path)(txt_path, exist_ok=True)
im_path = im_folder + gt_con
H, W, _ = H_W(im_path)
im_data = cv2.imread(im_path)
if im_data is None:
continue
numbox = int(gt.readline())
if numbox == 0:
gt.readline()
else:
os.makedirs(label_folder + file_dir_first, exist_ok = True)
with open(txt_path, 'w') as f_txt:
for i in range(numbox):
line = gt.readline()
infos = line.split(" ")
# x y w h .....
box = (int(infos[0]), int(infos[1]), int(infos[2]), int(infos[3]))
bbox = convert2yolo(box)
f_txt.write("%s %s %s %s %s\n" % (bbox[0], bbox[1], bbox[2], bbox[3], bbox[4]))