实现思路

  1. 输入要注册人脸的人姓名
  2. opencv调用摄像头获取帧
  3. 利用dlib库获取视频帧中人脸位置
  4. 截取人脸以文件的形式保存到本地文件夹,同一个人的人脸图像保存到同一个文件夹下,文件夹以所属者姓名命名

注意:cv.imwrite和cv.imread都不能识别中文路径!!!!

代码实现

# This is a sample Python script.
import os.path

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import cv2 as cv
import dlib

# 加载人脸检测器和关键点检测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")


# 人脸注册
def face_register(name):
cap = cv.VideoCapture(0)
face_num = 0
path = 'faces/' + name + '/'
if not os.path.exists(path):
os.makedirs(path)
while True:
ret, frame = cap.read()
if not ret:
print('摄像头异常')
break

# 检测人脸
faces = detector(frame, 1)
for i, face in enumerate(faces):
x1, y1, x2, y2 = face.left(), face.top(), face.right(), face.bottom()
landmarks = np.matrix([[p.x, p.y] for p in predictor(frame, face).parts()])
# 截取人脸区域并保存
# cv.imwrite(path+str(face_num) + '.jpg', frame[y1:y2, x1:x2])
cv.imencode('.jpg', frame[y1:y2, x1:x2])[1].tofile(path+str(face_num) + '.jpg')
face_num += 1
if face_num > 5:
break

# read
# img = cv.imdecode(np.fromfile(filepath, dtype=np.uint8), cv2.IMREAD_COLOR)
# 绘制68个特征点
for idx, point in enumerate(landmarks):
pos = (point[0, 0], point[0, 1])
cv.circle(frame, pos, 2, color=(0, 255, 0))
cv.imshow('video', frame)
# 检测按键,按下q退出循环 或者识别到5张就退出循环,关闭摄像头
if cv.waitKey(1) & 0xFF == ord('q') or face_num > 5:
break

cap.release()
cv.destroyAllWindows()

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
user_input = input("请输入姓名:")
print("您好," + user_input + "!\r\n我们现在开始进行人脸录入...")
face_register(user_input)
print('人脸录入成功!')