Here we will try to obtain all the neccessary features of face using Dlib's model shape_predictor_68_face_landmarks.
Here is our input image :
Let’s look at an code :
# Import neccessary libraries
import cv2
import dlib
import numpy
# Load shape_predictor_68_face_landmarks model
PREDICTOR_PATH = 'shape_predictor_68_face_landmarks.dat'
# Create predictor and detector
predictor = dlib.shape_predictor( PREDICTOR_PATH)
detector = dlib.get_frontal_face_detector()
# Create Exception for TooManyFaces to ignore
class TooManyFaces(Exception):
pass
# Create Exception for NoFaces to ignore
class NoFaces(Exception):
pass
# This function will obtain landmarks from image which is passed as parameter to it
def get_landmarks(im):
rects = detector(im,1)
if len(rects) > 1:
raise TooManyFaces
if len(rects) == 0:
raise NoFaces
return numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()])
# This Function will display landmarks on the image
def annotate_landmarks(im, landmarks):
im = im.copy()
# Loop through the landmark then number and circle features
for idx, point in enumerate(landmarks):
pos = (point[0,0], point[0,1])
cv2.putText(im, str(idx), pos, cv2.FONT_HERSHEY_SCRIPT_SIMPLEX , fontScale=0.4, color=(0,0,255))
cv2.circle(im,pos,3,color=(0,255,255))
# Return Marked image
return im
# Load our image
image = cv2.imread('faces.jpg')
# Call get_landmarks function
landmarks = get_landmarks(image)
# Call annotate_landmarks function to obtain marked image
image_with_landmarks = annotate_landmarks(image, landmarks)
# Display and write Marked image
cv2.imshow('Result', image_with_landmarks)
cv2.imwrite( 'image_with_landmarks.jpg', image_with_landmarks)
cv2.waitKey(0)
cv2.destroyAllWindows()
Our Output image will look like this: