__init__.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import time
  2. import numpy as np
  3. import cv2
  4. import torch
  5. from torchvision import transforms
  6. from .nets import S3FDNet
  7. from .box_utils import nms_
  8. PATH_WEIGHT = './detectors/s3fd/weights/sfd_face.pth'
  9. img_mean = np.array([104., 117., 123.])[:, np.newaxis, np.newaxis].astype('float32')
  10. class S3FD():
  11. def __init__(self, device='cuda'):
  12. tstamp = time.time()
  13. self.device = device
  14. print('[S3FD] loading with', self.device)
  15. self.net = S3FDNet(device=self.device).to(self.device)
  16. state_dict = torch.load(PATH_WEIGHT, map_location=self.device)
  17. self.net.load_state_dict(state_dict)
  18. self.net.eval()
  19. print('[S3FD] finished loading (%.4f sec)' % (time.time() - tstamp))
  20. def detect_faces(self, image, conf_th=0.8, scales=[1]):
  21. w, h = image.shape[1], image.shape[0]
  22. bboxes = np.empty(shape=(0, 5))
  23. with torch.no_grad():
  24. for s in scales:
  25. scaled_img = cv2.resize(image, dsize=(0, 0), fx=s, fy=s, interpolation=cv2.INTER_LINEAR)
  26. scaled_img = np.swapaxes(scaled_img, 1, 2)
  27. scaled_img = np.swapaxes(scaled_img, 1, 0)
  28. scaled_img = scaled_img[[2, 1, 0], :, :]
  29. scaled_img = scaled_img.astype('float32')
  30. scaled_img -= img_mean
  31. scaled_img = scaled_img[[2, 1, 0], :, :]
  32. x = torch.from_numpy(scaled_img).unsqueeze(0).to(self.device)
  33. y = self.net(x)
  34. detections = y.data
  35. scale = torch.Tensor([w, h, w, h])
  36. for i in range(detections.size(1)):
  37. j = 0
  38. while detections[0, i, j, 0] > conf_th:
  39. score = detections[0, i, j, 0]
  40. pt = (detections[0, i, j, 1:] * scale).cpu().numpy()
  41. bbox = (pt[0], pt[1], pt[2], pt[3], score)
  42. bboxes = np.vstack((bboxes, bbox))
  43. j += 1
  44. keep = nms_(bboxes, 0.1)
  45. bboxes = bboxes[keep]
  46. return bboxes