rishiswethan2

sefws

Jul 30th, 2019
470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. from imutils import face_utils
  2. import dlib
  3. import cv2
  4.  
  5. detector = dlib.get_frontal_face_detector()
  6. predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
  7.  
  8.  
  9. def getFacialLandmarks(image_dir='', img=None, showImg=True):
  10.  
  11. if len(image_dir) >= 1:
  12. image = cv2.imread(image_dir, flags=cv2.IMREAD_GRAYSCALE)
  13. else:
  14. # img = cv2.resize(img, (120, 90))
  15. image = img
  16. image = cv2.copyMakeBorder(image, 40, 40, 40, 40, cv2.BORDER_CONSTANT)
  17.  
  18. gray = image
  19.  
  20. # detect faces in the grayscale image
  21. rects = detector(gray, 1)
  22.  
  23. found_face = (False if len(rects) == 0 else True)
  24.  
  25. face_landmarks_all = []
  26. faces = []
  27. # loop over the face detections
  28. for (i, rect) in enumerate(rects):
  29. face_landmarks = []
  30.  
  31. print("rest", rect)
  32.  
  33. # convert dlib's rectangle to a OpenCV-style bounding box
  34. # [i.e., (x, y, w, h)], then draw the face bounding box
  35. (x, y, w, h) = face_utils.rect_to_bb(rect)
  36. x -= 10 if w < 100 else int(w / 8)
  37. y -= 10 if w < 100 else int(w / 8)
  38. w += 20 if w < 100 else int(w / 4)
  39. h += 20 if w < 100 else int(w / 4)
  40.  
  41. sub_face_ = image[y:y + h, x:x + w]
  42.  
  43. try:
  44. sub_face = cv2.resize(sub_face_, (100, 100))
  45. rec = detector(sub_face, 1)
  46. print("rec__"+str(len(rec)), list(rec))
  47. found_face = (False if ((len(rec) == 0) or (found_face == False)) else True)
  48. except:
  49. found_face = False
  50.  
  51. if found_face:
  52. print("Face", found_face)
  53. for (i, re) in enumerate(rec):
  54. sh = face_utils.shape_to_np(predictor(sub_face, re))
  55.  
  56. lands = []
  57. for (xx, yy) in sh:
  58. lands.append((xx, yy))
  59. cv2.circle(sub_face, (xx, yy), 0, (0, 255, 0), -1)
  60. face_landmarks.append(lands)
  61. if showImg:
  62. cv2.imshow(image_dir, sub_face)
  63. cv2.waitKey(0)
  64. faces.append(sub_face)
  65. face_landmarks_all.append(face_landmarks)
  66. # print(sh)
  67. else:
  68. if showImg:
  69. cv2.imshow(image_dir, image)
  70. cv2.waitKey(0)
  71. print("NOT FOUND")
  72.  
  73. return faces, face_landmarks_all, found_face
  74.  
  75. # print(getFacialLandmarks('test.jpg', False))
Add Comment
Please, Sign In to add comment