python人脸识别程序
人脸提取代码
# -*- coding: utf-8 -*-
import dlib
import cv2
import numpy as np
import glob
from imageio import imread
# 自己的脸
labeled = glob.glob('C:/Users/35419/Desktop/taizhimin/*.jpg')
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('model/shape_predictor_68_face_landmarks.dat')
facerec = dlib.face_recognition_model_v1('model/dlib_face_recognition_resnet_model_v1.dat')
camera = cv2.VideoCapture(0)
# 摄像头分辨率调低
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
labeled_data = {}
for path in labeled:
img = imread(path)
dets = detector(img, 1)
if dets:
shape = predictor(img, dets[0])
face_vector = facerec.compute_face_descriptor(img, shape)
labeled_data[path] = face_vector
def distance(a, b):
return np.linalg.norm(np.array(a) - np.array(b), ord=2)
if not camera.isOpened():
print("cannot open camear")
exit(0)
b = True
x = False
while True:
ret, frame = camera.read()
if not ret:
continue
cv2.imshow("Camera", frame)
frame_new = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 每四贞检测一次,希望稍微快一点吧
if b | b ^ x:
b = x
continue
# 检测脸部
dets = detector(frame_new, 1)
if dets:
for i, face in enumerate(dets):
shape = predictor(frame_new, dets[0])
face_vector = facerec.compute_face_descriptor(frame_new, shape)
for key, value in labeled_data.items():
d = distance(face_vector, value)
if d < 0.4:
cv2.putText(frame, 'taizhimin', (0, 30), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (255, 255, 255), 1, cv2.LINE_AA)
cv2.rectangle(frame, (face.left(), face.top()), (face.right(), face.bottom()),
(0, 255, 0),
3)
cv2.imshow("Camera", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()