retinaface2yolo.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import os
  2. import os.path
  3. import sys
  4. import torch
  5. import torch.utils.data as data
  6. import cv2
  7. import numpy as np
  8. class WiderFaceDetection(data.Dataset):
  9. def __init__(self, txt_path, preproc=None):
  10. self.preproc = preproc
  11. self.imgs_path = []
  12. self.words = []
  13. f = open(txt_path,'r')
  14. lines = f.readlines()
  15. isFirst = True
  16. labels = []
  17. for line in lines:
  18. line = line.rstrip()
  19. if line.startswith('#'):
  20. if isFirst is True:
  21. isFirst = False
  22. else:
  23. labels_copy = labels.copy()
  24. self.words.append(labels_copy)
  25. labels.clear()
  26. path = line[2:]
  27. path = txt_path.replace('label.txt','images/') + path
  28. self.imgs_path.append(path)
  29. else:
  30. line = line.split(' ')
  31. label = [float(x) for x in line]
  32. labels.append(label)
  33. self.words.append(labels)
  34. def __len__(self):
  35. return len(self.imgs_path)
  36. def __getitem__(self, index):
  37. img = cv2.imread(self.imgs_path[index])
  38. height, width, _ = img.shape
  39. labels = self.words[index]
  40. annotations = np.zeros((0, 15))
  41. if len(labels) == 0:
  42. return annotations
  43. for idx, label in enumerate(labels):
  44. annotation = np.zeros((1, 15))
  45. # bbox
  46. annotation[0, 0] = label[0] # x1
  47. annotation[0, 1] = label[1] # y1
  48. annotation[0, 2] = label[0] + label[2] # x2
  49. annotation[0, 3] = label[1] + label[3] # y2
  50. # landmarks
  51. annotation[0, 4] = label[4] # l0_x
  52. annotation[0, 5] = label[5] # l0_y
  53. annotation[0, 6] = label[7] # l1_x
  54. annotation[0, 7] = label[8] # l1_y
  55. annotation[0, 8] = label[10] # l2_x
  56. annotation[0, 9] = label[11] # l2_y
  57. annotation[0, 10] = label[13] # l3_x
  58. annotation[0, 11] = label[14] # l3_y
  59. annotation[0, 12] = label[16] # l4_x
  60. annotation[0, 13] = label[17] # l4_y
  61. if (annotation[0, 4]<0):
  62. annotation[0, 14] = -1
  63. else:
  64. annotation[0, 14] = 1
  65. annotations = np.append(annotations, annotation, axis=0)
  66. target = np.array(annotations)
  67. if self.preproc is not None:
  68. img, target = self.preproc(img, target)
  69. return torch.from_numpy(img), target
  70. def detection_collate(batch):
  71. """Custom collate fn for dealing with batches of images that have a different
  72. number of associated object annotations (bounding boxes).
  73. Arguments:
  74. batch: (tuple) A tuple of tensor images and lists of annotations
  75. Return:
  76. A tuple containing:
  77. 1) (tensor) batch of images stacked on their 0 dim
  78. 2) (list of tensors) annotations for a given image are stacked on 0 dim
  79. """
  80. targets = []
  81. imgs = []
  82. for _, sample in enumerate(batch):
  83. for _, tup in enumerate(sample):
  84. if torch.is_tensor(tup):
  85. imgs.append(tup)
  86. elif isinstance(tup, type(np.empty(0))):
  87. annos = torch.from_numpy(tup).float()
  88. targets.append(annos)
  89. return (torch.stack(imgs, 0), targets)
  90. save_path = '/ssd_1t/derron/yolov5-face/data/widerface/train'
  91. aa=WiderFaceDetection("/ssd_1t/derron/yolov5-face/data/widerface/widerface/train/label.txt")
  92. for i in range(len(aa.imgs_path)):
  93. print(i, aa.imgs_path[i])
  94. img = cv2.imread(aa.imgs_path[i])
  95. base_img = os.path.basename(aa.imgs_path[i])
  96. base_txt = os.path.basename(aa.imgs_path[i])[:-4] +".txt"
  97. save_img_path = os.path.join(save_path, base_img)
  98. save_txt_path = os.path.join(save_path, base_txt)
  99. with open(save_txt_path, "w") as f:
  100. height, width, _ = img.shape
  101. labels = aa.words[i]
  102. annotations = np.zeros((0, 14))
  103. if len(labels) == 0:
  104. continue
  105. for idx, label in enumerate(labels):
  106. annotation = np.zeros((1, 14))
  107. # bbox
  108. label[0] = max(0, label[0])
  109. label[1] = max(0, label[1])
  110. label[2] = min(width - 1, label[2])
  111. label[3] = min(height - 1, label[3])
  112. annotation[0, 0] = (label[0] + label[2] / 2) / width # cx
  113. annotation[0, 1] = (label[1] + label[3] / 2) / height # cy
  114. annotation[0, 2] = label[2] / width # w
  115. annotation[0, 3] = label[3] / height # h
  116. #if (label[2] -label[0]) < 8 or (label[3] - label[1]) < 8:
  117. # img[int(label[1]):int(label[3]), int(label[0]):int(label[2])] = 127
  118. # continue
  119. # landmarks
  120. annotation[0, 4] = label[4] / width # l0_x
  121. annotation[0, 5] = label[5] / height # l0_y
  122. annotation[0, 6] = label[7] / width # l1_x
  123. annotation[0, 7] = label[8] / height # l1_y
  124. annotation[0, 8] = label[10] / width # l2_x
  125. annotation[0, 9] = label[11] / height # l2_y
  126. annotation[0, 10] = label[13] / width # l3_x
  127. annotation[0, 11] = label[14] / height # l3_y
  128. annotation[0, 12] = label[16] / width # l4_x
  129. annotation[0, 13] = label[17] / height # l4_y
  130. str_label="0 "
  131. for i in range(len(annotation[0])):
  132. str_label =str_label+" "+str(annotation[0][i])
  133. str_label = str_label.replace('[', '').replace(']', '')
  134. str_label = str_label.replace(',', '') + '\n'
  135. f.write(str_label)
  136. cv2.imwrite(save_img_path, img)