Skip to content

Instantly share code, notes, and snippets.

@shivanandmn
Created March 5, 2021 00:43
Show Gist options
  • Save shivanandmn/8a26186a6d0dbe3e49ae02afd48bd5ff to your computer and use it in GitHub Desktop.
Save shivanandmn/8a26186a6d0dbe3e49ae02afd48bd5ff to your computer and use it in GitHub Desktop.
Detecting face and landmarks from image using dlib and opencv
#pip install dlib
#download pretrained dlib file and unzip
#$wget http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
#$bzip2 -d /content/shape_predictor_68_face_landmarks.dat.bz2
import sys
import numpy as np
import cv2
#below line of code is used only in colab
from google.colab.patches import cv2_imshow
import dlib
pretrained_dlib_detector = "/content/shape_predictor_68_face_landmarks.dat"
detector = detector = dlib.get_frontal_face_detector()
#frame is a 3-channel image
rects = detector(frame, 1)
predictor = dlib.shape_predictor(pretrained_dlib_detector)
def rect_to_bb(rect):
# take a bounding predicted by dlib and convert it
# to the format (x, y, w, h) as we would normally do
# with OpenCV
x = rect.left()
y = rect.top()
w = rect.right() - x
h = rect.bottom() - y
# return a tuple of (x, y, w, h)
return (x, y, w, h)
def shape_to_np(shape, dtype="int"):
# initialize the list of (x, y)-coordinates
coords = np.zeros((68, 2), dtype=dtype)
# loop over the 68 facial landmarks and convert them
# to a 2-tuple of (x, y)-coordinates
for i in range(0, 68):
coords[i] = (shape.part(i).x, shape.part(i).y)
# return the list of (x, y)-coordinates
return coords
for (i, rect) in enumerate(rects):
# determine the facial landmarks for the face region, then
# convert the facial landmark (x, y)-coordinates to a NumPy
# array
shape = predictor(frame, rect)
shape = shape_to_np(shape)
# convert dlib's rectangle to a OpenCV-style bounding box
# [i.e., (x, y, w, h)], then draw the face bounding box
(x, y, w, h) = rect_to_bb(rect)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# show the face number
cv2.putText(frame, "Face #{}".format(i + 1), (x - 10, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# loop over the (x, y)-coordinates for the facial landmarks
# and draw them on the image
for (x, y) in shape:
cv2.circle(frame, (x, y), 1, (0, 0, 255), -1)
# show the output image with the face detections + facial landmarks
#below is used only in colab
cv2_imshow(frame)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment