基于insightface实现人脸1:1

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()

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值