I am trying to do face alignment code in python. I am following this article but in this article for face detection dlib is used. Below is the original code:
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
import argparse
import imutils
import dlib
import cv2
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
fa = FaceAligner(predictor, desiredFaceWidth=256)
image = cv2.imread('images\\1.jpg')
image = imutils.resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 2)
for rect in rects:
(x, y, w, h) = rect_to_bb(rect)
faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256)
faceAligned = fa.align(image, gray, rect) # Here we get the aligned face
I have some face images which are not getting detected by dlib face detector. So I am modifying above code and using DNN face detection. Below is my code:
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
import argparse
import imutils
import dlib
import cv2
protoPath = "deploy.prototxt"
modelPath = "res10_300x300_ssd_iter_140000.caffemodel"
detector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)
fa = FaceAligner(predictor, desiredFaceWidth=256)
image = cv2.imread('images\\1.jpg')
image = imutils.resize(image, width=300)
(h, w) = image.shape[:2]
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
imageBlob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0), swapRB=False, crop=False)
detector.setInput(imageBlob)
detections = detector.forward()
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
face = image[startY:endY, startX:endX]
gray = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
r = dlib.rectangle(int(startX), int(startY), int(endX), int(endY))
faceAligned = fa.align(face, gray, r)
But in above code faceAligned
is all zeros and thus a blank image. I am not sure what I am doing wrong. Can anyone please point out the mistake and help me resolve the issue. Please help. Thanks