[Python] 纯文本查看 复制代码
import dlib
import numpy as np
import cv2
import pyttsx3
import time
def rect_to_bb(rect): # 获得人脸矩形的坐标信息
x = rect.left()
y = rect.top()
w = rect.right() - x
h = rect.bottom() - y
return (x, y, w, h)
def shape_to_np(shape, dtype="int"): # 将包含68个特征的的shape转换为numpy array格式
coords = np.zeros((68, 2), dtype=dtype)
for i in range(0, 68):
coords[i] = (shape.part(i).x, shape.part(i).y)
return coords
def resize(image, width=1200): # 将待检测的image进行resize
r = width * 1.0 / image.shape[1]
dim = (width, int(image.shape[0] * r))
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
return resized
def feature(gray,detector,predictor,face_reco_model):
rects = detector(gray, 1)
shape = predictor(gray, rects[0])
res_128 = face_reco_model.compute_face_descriptor(gray, shape)
return res_128,rects[0]
def main(paths,cosis=True):
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("./data/data_dlib/shape_predictor_68_face_landmarks.dat")
#人脸识别
face_reco_model = dlib.face_recognition_model_v1("D:/download/windows/Dlib_face_recognition_from_camera-master/Dlib_face_recognition_from_camera-master/data/data_dlib/dlib_face_recognition_resnet_model_v1.dat")
cap = cv2.VideoCapture(0) # Get video stream from camera
cap.set(3, 480)
# try:
if cap.isOpened():
flag, img_rd = cap.read()
# #人脸检测
# cv2.imshow("faces",img_rd)
# cv2.waitKey(0)
img_rd = resize(img_rd, width=1200)
# img_rd = cv2.imread("C:/Users/ljl/Pictures/0112.jpg")
img_other_array,rect2 = feature(img_rd,detector,predictor,face_reco_model)
cap.release()
# except Exception as e:
# print(e)
#初始化语音播报
engine = pyttsx3.init()
res_sim_dict = {}
for name,path in paths.items():
image = cv2.imread(path)
image = resize(image, width=1200)
img_array,rect1 = feature(image,detector,predictor,face_reco_model)
A = np.array(img_array)
B = np.array(img_other_array)
if cosis:
#余弦相似度
org_new = np.dot(A,B)
orginal = np.linalg.norm(A)
new = np.linalg.norm(B)
res_sim = org_new/(orginal*new)
res_sim_dict[name] = res_sim
else:
#欧式距离相似度
res_sim = np.sqrt(np.sum((A-B)**2))
res_sim_dict[name] = 1/(1+res_sim)
# res_sim_list.append(1/(1+res_sim)) #为了流程统一,取距离加一的倒数来度量 人脸的相似度
# sorted(别名相似度字典.items(), key = lambda kv:(kv[1], kv[0]),reverse=True)
res_sim_sort = sorted(res_sim_dict.items(),key=lambda x:x[1],reverse=True)[:1]
for name,res_sim in res_sim_dict.items():
print(res_sim)
if name==res_sim_sort[0][0]:
res_content = "{}".format(name)
else:
res_content = "检测未通过"
engine.say(res_content)
# 等待语音播报完毕
engine.runAndWait()
cv2.destroyAllWindows()
return res_sim_dict