val2yolo_for_test.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import os
  2. import cv2
  3. import numpy as np
  4. import shutil
  5. from tqdm import tqdm
  6. root = '/ssd_1t/derron/WiderFace'
  7. def xywh2xxyy(box):
  8. x1 = box[0]
  9. y1 = box[1]
  10. x2 = box[0] + box[2]
  11. y2 = box[1] + box[3]
  12. return (x1, x2, y1, y2)
  13. def convert(size, box):
  14. dw = 1. / (size[0])
  15. dh = 1. / (size[1])
  16. x = (box[0] + box[1]) / 2.0 - 1
  17. y = (box[2] + box[3]) / 2.0 - 1
  18. w = box[1] - box[0]
  19. h = box[3] - box[2]
  20. x = x * dw
  21. w = w * dw
  22. y = y * dh
  23. h = h * dh
  24. return (x, y, w, h)
  25. def wider2face(phase='val', ignore_small=0):
  26. data = {}
  27. with open('{}/{}/label.txt'.format(root, phase), 'r') as f:
  28. lines = f.readlines()
  29. for line in tqdm(lines):
  30. line = line.strip()
  31. if '#' in line:
  32. path = '{}/{}/images/{}'.format(root, phase, os.path.basename(line))
  33. img = cv2.imread(path)
  34. height, width, _ = img.shape
  35. data[path] = list()
  36. else:
  37. box = np.array(line.split()[0:4], dtype=np.float32) # (x1,y1,w,h)
  38. if box[2] < ignore_small or box[3] < ignore_small:
  39. continue
  40. box = convert((width, height), xywh2xxyy(box))
  41. label = '0 {} {} {} {} -1 -1 -1 -1 -1 -1 -1 -1 -1 -1'.format(round(box[0], 4), round(box[1], 4),
  42. round(box[2], 4), round(box[3], 4))
  43. data[path].append(label)
  44. return data
  45. if __name__ == '__main__':
  46. datas = wider2face('val')
  47. for idx, data in enumerate(datas.keys()):
  48. pict_name = os.path.basename(data)
  49. out_img = 'widerface/val/images/{}'.format(pict_name)
  50. out_txt = 'widerface/val/labels/{}.txt'.format(os.path.splitext(pict_name)[0])
  51. shutil.copyfile(data, out_img)
  52. labels = datas[data]
  53. f = open(out_txt, 'w')
  54. for label in labels:
  55. f.write(label + '\n')
  56. f.close()