概况:
使用OpenCv,dlib人脸识别库进行人脸实时识别
程序说明:
get_face.py:对人脸进行拍照,并将人脸图片保存。
save_csv.py:读取保存的人脸图片,提取人脸的128D特征值存入csv文件。
face_detect.py:打开摄像头进行人脸的实时识别。
程序示例:
get_face.py
import cv2
# 打开摄像头,0代表内置摄像头,1代表外置摄像头
camera = cv2.VideoCapture(0)
while True:
ret, frame = camera.read()
cv2.imshow('', frame)
# 按q键拍照保存图片并退出
if cv2.waitKey(1) == ord('q'):
cv2.imwrite('人脸.png', frame)
break
# 释放摄像头资源
camera.release()
cv2.destroyAllWindows()
save_csv.py
import csv
import dlib
from skimage import io
import cv2
# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# Dlib 人脸预测器
predictor = dlib.shape_predictor('data/data_dlib/shape_predictor_68_face_landmarks.dat')
# Dlib 人脸识别模型
facerec = dlib.face_recognition_model_v1('data/data_dlib/dlib_face_recognition_resnet_model_v1.dat')
# 返回单张图像的 128D 特征
def feature(img):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
faces = detector(img_gray, 1)
if len(faces) != 0:
shape = predictor(img_gray, faces[0])
descriptor = facerec.compute_face_descriptor(img_gray, shape)
else:
descriptor = 0
return descriptor
# 将照片特征提取出来, 写入 CSV
def write_csv(face_path, csv_path):
image = io.imread(face_path)
feature_128d = feature(image)
with open('data.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(feature_128d)
if __name__ == '__main__':
write_csv('人脸.png', 'data.csv')
face_detect.py
import cv2
import dlib
import pandas as pd
import numpy as np
# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# Dlib 人脸预测器
predictor = dlib.shape_predictor('data/data_dlib/shape_predictor_68_face_landmarks.dat')
# Dlib 人脸识别模型
facerec = dlib.face_recognition_model_v1('data/data_dlib/dlib_face_recognition_resnet_model_v1.dat')
# 计算两个128D向量间的欧式距离
def distance(feature_1, feature_2):
feature_1 = np.array(feature_1)
feature_2 = np.array(feature_2)
dist = np.linalg.norm(feature_1 - feature_2)
if dist > 0.4:
return False
else:
return True
# 处理存放所有人脸特征的 csv
csv_rd = pd.read_csv('data.csv', header=None)
# 用来存放所有录入人脸特征的数组
known_arr = []
# 读取已知人脸数据
for i in range(csv_rd.shape[0]):
someone_arr = []
for j in range(0, len(csv_rd.ix[i, :])):
someone_arr.append(csv_rd.ix[i, :][j])
known_arr.append(someone_arr)
camera = cv2.VideoCapture(0)
while True:
ret, frame = camera.read()
# 取灰度
img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 人脸数 faces
faces = detector(img_gray, 0)
# 存储当前摄像头中捕获到的所有人脸的名字
namelist = []
# 按下 q 键退出
if cv2.waitKey(1) == ord('q'):
break
else:
# 检测到人脸
if len(faces) != 0:
feature_arr = []
# 获取当前捕获到的图像的所有人脸的特征,存储到 feature_arr
for i in range(len(faces)):
shape = predictor(img_gray, faces[i])
feature_arr.append(facerec.compute_face_descriptor(img_gray, shape))
# 遍历捕获到的图像中所有的人脸
for k in range(len(faces)):
# 先默认所有人不认识,是 unknown
namelist.append('unknown')
# 对于某张人脸,遍历所有存储的人脸特征
for i in range(len(known_arr)):
# 将某张人脸与存储的所有人脸数据进行比对
compare = distance(feature_arr[k], known_arr[i])
# 找到了相似脸
if compare == True:
if i == 0:
namelist[k] = 'wei'
# 绘制矩形框
for kk, d in enumerate(faces):
cv2.rectangle(frame, (d.left(), d.top()), (d.right(), d.bottom()), (0, 255, 0), 2)
# 在人脸框下面写人脸名字
for i in range(len(faces)):
cv2.putText(frame, namelist[i], (faces[i].left(), faces[i].top()), 0, 1.5, (0, 255, 0), 2)
cv2.imshow('', frame)
# 释放摄像头
camera.release()
# 删除建立的窗口
cv2.destroyAllWindows()