import cv2
import insightface
import numpy as np
from sklearn import preprocessing
import random
cap = cv2.VideoCapture(0)
app = insightface.app.FaceAnalysis(name='buffalo_l', providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
app.prepare(ctx_id=0, det_size=(640, 640))
img_path = '张学友.jpg'
img_name = img_path.split('.')[0]
img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
face_info = {}
faces = app.get(img)
embedding = np.array(faces[0].embedding).reshape((1,-1))
embedding = preprocessing.normalize(embedding)
img_name = img_path.split('.')[0]
face_info.update({img_name:embedding})
print(face_info)
for face in faces:
bbox = face.bbox.astype(int)
cv2.rectangle(img,(bbox[0],bbox[1]),(bbox[2],bbox[3]),(0,255,0),2)
for k in face.landmark_3d_68:
x,y,z = k.astype(int)
cv2.circle(img,(x,y),1,(0, 0, 255), -1)
def num1(cosine_similarity):
if cosine_similarity > 0.6:
return '是同一人'
else:
return '不是同一人'
def num2(face_gender):
if face_gender ==0:
return '女'
else:
return '男'
while True:
ret, img2 = cap.read()
faces2 = app.get(img2)
for face in faces2:
embedding2 = np.array(face.embedding).reshape((1, -1))
embedding2 = preprocessing.normalize(embedding2)
bbox = face.bbox.astype(int)
cv2.rectangle(img2, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
for k in face.landmark_3d_68:
x, y, z = k.astype(int)
cv2.circle(img2, (x, y), 1, (0, 0, 255), -1)
dot_embedding = np.dot(embedding,embedding2.T)
norm_embedding = np.linalg.norm(embedding)
norm_embedding2 = np.linalg.norm(embedding2)
cosine_similarity = dot_embedding / (norm_embedding*norm_embedding2)
a = num1(cosine_similarity=cosine_similarity)
b = num2(face.gender if hasattr(face, 'gender') else None)
c = random.randint(20,40)
cv2.putText(img2,b,(50,50),cv2.FONT_HERSHEY_SIMPLEX,0.75,(255,0,0),2)
cv2.putText(img2,str(c),(50,100),cv2.FONT_HERSHEY_SIMPLEX,0.75,(255,0,0),2)
cv2.putText(img2, a, (50, 150), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 0, 0), 2)
cv2.imshow('result',img2)
if cv2.waitKey(1) == ord("q"):
break
# cv2.imshow('zhang',img)
# cv2.waitKey(0)
cv2.destroyAllWindows()
cap.release()
基于insightface实现人脸1:1
于 2024-07-03 22:14:15 首次发布