Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Facial LandMarks extraction Python

Hey there! I am trying to extract 6-8 face landmarks. I use Python as compiler, face detection from OpenCV and facial landmarks detection from Dlib. The thing is the program extracts 68 of them. And i want some specifics one. The code is:

import cv2
import dlib
import numpy 

PREDICTOR_PATH = "C:\Python27\Lib\site-packages\dlib\shape_predictor_68_face_landmarks.dat"
predictor = dlib.shape_predictor(PREDICTOR_PATH)
cascade_path='C:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml'
cascade = cv2.CascadeClassifier(cascade_path)

def get_landmarks(im):
    rects = cascade.detectMultiScale(im, 1.3,5)
    x,y,w,h =rects[0]
    rect=dlib.rectangle(x,y,x+w,y+h)
    return numpy.matrix([[p.x, p.y] for p in predictor(im, rect).parts()])

def annotate_landmarks(im, landmarks):
    im = im.copy()
    for idx, point in enumerate(landmarks):
        pos = (point[0, 0], point[0, 1])
        cv2.putText(im, str(idx), pos,
                    fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
                    fontScale=0.4,
                    color=(0, 0, 255))
        cv2.circle(im, pos, 3, color=(0, 255, 255))
        print point, idx
    return im

im=cv2.imread('fa.jpg')
cv2.imshow('Result',annotate_landmarks(im,get_landmarks(im)))
cv2.waitKey(0)
cv2.destroyAllWindows()

There is a line code i don't understand and i believe it's the key for specific marks extraction.

pos = (point[0, 0], point[0, 1])< If i change the lane for idx, point in enumerate(landmarks): to for idx, point in enumerate(landmarks[8]): i will get only one facial mark (the chin one. 8 is the index of that point). But i can't put more specific points there because i will get this error:

TypeError: 'list' object cannot be interpreted as an index

Any idea guys? ^^