Unlock Powerful Face Recognition with Python’s face_recognition Library
This article introduces the open‑source Python library face_recognition, explains how to install it, locate and extract faces, generate 128‑dimensional embeddings, compare faces, detect facial landmarks, apply virtual makeup, and build a simple custom face‑recognition application with complete code examples and visual results.
face_recognition is a powerful, simple, and easy‑to‑use open‑source face recognition project that comes with comprehensive documentation and example applications, and it is compatible with Raspberry Pi.
The project’s source code is available at https://github.com/ageitgey/face_recognition.
Install the library via pip install face_recognition and verify the installation with a quick test.
1. Locate faces in an image
def demoFunc():
'''
在一张包含人脸的图片中圈出来人脸
'''
image = face_recognition.load_image_file("test.jpg")
face_locations = face_recognition.face_locations(image)
for one in face_locations:
y0, x1, y1, x0 = one
cv2.rectangle(image, pt1=(x0, y0), pt2=(x1, y1), color=(0, 0, 255), thickness=3)
cv2.imshow('aaa', image)
if cv2.waitKey(0) & 0xFF == ord('q'):
cv2.destroyAllWindows()Resulting detection image:
2. Crop each detected face and save locally
def demoFunc():
'''
图片中人脸截图保存
'''
img = cv2.imread("test.jpg")
image = face_recognition.load_image_file("test.jpg")
face_locations = face_recognition.face_locations(image) #(top, right, bottom, left)
for i in range(len(face_locations)):
y0, x1, y1, x0 = face_locations[i]
cropped = img.crop((x0, y0, x1, y1)) # (left, upper, right, lower)
cropped.save(str(i) + "_.jpg")
cropped.show()Cropped face results:
3. Encode each face into a 128‑dimensional vector
def demoFunc():
'''
将图片中的每张人脸编码成一个128维长度的向量
'''
image = face_recognition.load_image_file("cl.jpg")
face_locations = face_recognition.face_locations(image) #(top, right, bottom, left)
face_encodings = face_recognition.face_encodings(image, face_locations) # 将单个人脸数据转化为一个128维的向量
for one in face_encodings:
print('one: ', one)Example vector output (using a picture of Jackie Chan):
4. Compare two face images to determine if they belong to the same person
def demoFunc(one_pic='c1.jpg', two_pic='c2.jpg'):
'''
给定两张图片,判断是否是同一个人
'''
chenglong = face_recognition.load_image_file(one_pic)
unknown_image = face_recognition.load_image_file(two_pic)
biden_encoding = face_recognition.face_encodings(chenglong)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
results = face_recognition.compare_faces([biden_encoding], unknown_encoding)
print('results: ', results)
return results[0]Comparison result image:
5. Detect facial landmarks and annotate them
def demoFunc(pic_path='cl.jpg'):
'''
脸部关键点识别、标注
'''
image = face_recognition.load_image_file(pic_path)
face_landmarks_list = face_recognition.face_landmarks(image)
print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)
for face_landmarks in face_landmarks_list:
for facial_feature in face_landmarks.keys():
print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature]))
for facial_feature in face_landmarks.keys():
d.line(face_landmarks[facial_feature], width=5)
pil_image.show()Landmark visualization results:
6. Apply virtual makeup using facial landmarks
def demoFunc(pic_path="haiwang.jpg"):
'''
化妆
'''
image = face_recognition.load_image_file(pic_path)
face_landmarks_list = face_recognition.face_landmarks(image)
pil_image = Image.fromarray(image)
for face_landmarks in face_landmarks_list:
demo = ImageDraw.Draw(pil_image, 'RGBA')
demo.polygon(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 128))
demo.polygon(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 128))
demo.line(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 150), width=2)
demo.line(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 150), width=2)
demo.polygon(face_landmarks['top_lip'], fill=(150, 0, 0, 128))
demo.polygon(face_landmarks['bottom_lip'], fill=(150, 0, 0, 128))
demo.line(face_landmarks['top_lip'], fill=(150, 0, 0, 64), width=2)
demo.line(face_landmarks['bottom_lip'], fill=(150, 0, 0, 64), width=2)
demo.polygon(face_landmarks['left_eye'], fill=(255, 255, 255, 30))
demo.polygon(face_landmarks['right_eye'], fill=(255, 255, 255, 30))
demo.line(face_landmarks['left_eye'] + [face_landmarks['left_eye'][0]], fill=(0, 0, 0, 110), width=2)
demo.line(face_landmarks['right_eye'] + [face_landmarks['right_eye'][0]], fill=(0, 0, 0, 110), width=2)
pil_image.show()Virtual‑makeup results:
7. Build a simple face‑recognition application
def faceRecognitionDemo(picDir='data/', test_pic='test.png'):
'''
基于 face_recognition 构建人脸识别模块
'''
pic_list = os.listdir(picDir)
for one_pic in pic_list:
one_pic_path = picDir + one_pic
one_res = demo6(one_pic=one_pic_path, two_pic=test_pic)
one_name = one_pic.split('.')[0].strip()
if one_res:
print('This Person is: ', one_name)
break
else:
print('This Person is not: ', one_name)Application output screenshot:
The face_recognition library essentially converts each face image into a 128‑dimensional feature vector; similarity between vectors determines identity, and the process can be extended with machine‑learning classifiers such as SVM, Random Forest, or Gradient Boosting for more robust recognition.
Original article: https://yishuihancheng.blog.csdn.net/article/details/102831117
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.
