人脸识别.Dlib
1.安装依赖
pip install dlib
2.案例分析
# -*- coding:utf-8 -*-
import os
import dlib
import cv2
import numpy as np
def dlib_face_detection_demo(image_path, save_path="detected_face.jpg"):
detector = dlib.get_frontal_face_detector()
def cv_imread(file_path):
stream = open(file_path, 'rb')
bytes = bytearray(stream.read())
numpy_array = np.asarray(bytes, dtype=np.uint8)
return cv2.imdecode(numpy_array, cv2.IMREAD_COLOR)
img = cv_imread(image_path)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector(gray_img, 1)
print(f"检测到 {len(faces)} 个人脸!")
for i, face in enumerate(faces):
x1, y1 = face.left(), face.top()
x2, y2 = face.right(), face.bottom()
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.putText(img, f"Face {i+1}", (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
cv2.imwrite(save_path, img)
print(f"检测结果已保存到:{save_path}")
cv2.imshow("Dlib Face Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
import sys
test_image_path = sys.argv[1]
dlib_face_detection_demo(test_image_path)







