Build a Face Recognition System in Under 40 Lines of Python with Dlib
This tutorial walks you through setting up a simple face‑recognition pipeline using Dlib and scikit‑image in Python, covering required tools, data preparation, the recognition workflow, and a complete 40‑line script with sample images and execution results.
Introduction
Many people think face recognition is extremely difficult, but implementing a basic recognizer can be done with fewer than 40 lines of Python code using Dlib.
Distinguishing Detection from Recognition
Face detection determines whether a face exists in an image, while face recognition identifies whose face it is; detection is a prerequisite for recognition.
Tools
Anaconda 2 – Python 2
Dlib
scikit-image
Dlib
Dlib is a modern C++‑based cross‑platform library offering machine‑learning, image‑processing, and numerical algorithms, with a well‑documented Python API. Install it via: pip install dlib Install scikit‑image similarly:
pip install scikit-imageFace Recognition Workflow
The process consists of three steps:
Detect faces in candidate images, extract landmarks, and compute descriptors, then store them.
Detect faces in the test image, extract landmarks, and compute its descriptor.
Calculate Euclidean distances between the test descriptor and each candidate descriptor; the smallest distance indicates the matching person.
Code
The following script girl-face-rec.py implements the above steps. It expects four command‑line arguments: the landmark model file, the face‑recognition model file, the folder containing candidate face images, and the test image path.
# -*- coding: UTF-8 -*-
import sys,os,dlib,glob,numpy
from skimage import io
if len(sys.argv) != 5:
print "请检查参数是否正确"
exit()
# 1. 人脸关键点检测器路径
predictor_path = sys.argv[1]
# 2. 人脸识别模型路径
face_rec_model_path = sys.argv[2]
# 3. 候选人脸文件夹路径
faces_folder_path = sys.argv[3]
# 4. 待识别的人脸图片路径
img_path = sys.argv[4]
# 加载检测器和模型
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor(predictor_path)
facerec = dlib.face_recognition_model_v1(face_rec_model_path)
descriptors = []
# 处理候选人脸
for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")):
print "Processing file: {}".format(f)
img = io.imread(f)
dets = detector(img, 1)
for d in dets:
shape = sp(img, d)
face_descriptor = facerec.compute_face_descriptor(img, shape)
v = numpy.array(face_descriptor)
descriptors.append(v)
# 处理待识别的人脸
img = io.imread(img_path)
dets = detector(img, 1)
dist = []
for d in dets:
shape = sp(img, d)
face_descriptor = facerec.compute_face_descriptor(img, shape)
d_test = numpy.array(face_descriptor)
for i in descriptors:
dist.append(numpy.linalg.norm(i - d_test))
candidate = ['Unknown1','Unknown2','Shishi','Unknown4','Bingbing','Feifei']
# 将候选人和距离配对并排序
c_d = dict(zip(candidate, dist))
cd_sorted = sorted(c_d.iteritems(), key=lambda d: d[1])
print "
The person is: ", cd_sorted[0][0]
dlib.hit_enter_to_continue()Running the Script
Place the trained model files shape_predictor_68_face_landmarks.dat and dlib_face_recognition_resnet_model_v1.dat (renamed to 1.dat and 2.dat for brevity) in the working directory, then execute:
python girl-face-rec.py 1.dat 2.dat ./candidate-faces test1.jpgThe output identifies the test image as “Bingbing”. Different test images may yield varying results, illustrating the need for further improvements such as using multiple candidate images per person and averaging distances.
Images
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
