val2yolo.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import os
  2. import cv2
  3. import numpy as np
  4. import shutil
  5. import sys
  6. from tqdm import tqdm
  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(root, 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, line.split()[-1])
  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. if len(sys.argv) == 1:
  47. print('Missing path to WIDERFACE folder.')
  48. print('Run command: python3 val2yolo.py /path/to/original/widerface [/path/to/save/widerface/val]')
  49. exit(1)
  50. elif len(sys.argv) > 3:
  51. print('Too many arguments were provided.')
  52. print('Run command: python3 val2yolo.py /path/to/original/widerface [/path/to/save/widerface/val]')
  53. exit(1)
  54. root_path = sys.argv[1]
  55. if not os.path.isfile(os.path.join(root_path, 'val', 'label.txt')):
  56. print('Missing label.txt file.')
  57. exit(1)
  58. if len(sys.argv) == 2:
  59. if not os.path.isdir('widerface'):
  60. os.mkdir('widerface')
  61. if not os.path.isdir('widerface/val'):
  62. os.mkdir('widerface/val')
  63. save_path = 'widerface/val'
  64. else:
  65. save_path = sys.argv[2]
  66. datas = wider2face(root_path, phase='val')
  67. for idx, data in enumerate(datas.keys()):
  68. pict_name = os.path.basename(data)
  69. out_img = f'{save_path}/{idx}.jpg'
  70. out_txt = f'{save_path}/{idx}.txt'
  71. shutil.copyfile(data, out_img)
  72. labels = datas[data]
  73. f = open(out_txt, 'w')
  74. for label in labels:
  75. f.write(label + '\n')
  76. f.close()