小白求助!求大神帮我看看哪里错了呢?一运行就报错。

# 1、导入库
import cv2
import dlib
import numpy as np


# 定义:关键点编码为128维
def encoder_face(img, detector, predictor, encoder, upsample=1, jet=1):  # 默认设置upsample=1,jet=1
    # 检测人脸
    faces = detector(img, upsample)
    # 对每张人脸进行关键点检测
    # gray = cv2.cvtColor((img,cv2.COLOR_BGRA2GRAY))     # 不用灰度图片
    faces_keypoints = [predictor(img, face) for face in faces]  # 提取人脸关键点,(列表推导式)
    """
    注意!!要转换为np.array(数组),这样返回的才是特征向量的列表。
    """
    return [np.array(encoder.compute_face_descriptor(img, faces_keypoint, jet)) for faces_keypoint in faces_keypoints]


"""
欧式距离
"""
# 定义:人脸比较,通过【欧氏距离】
def compare_faces(face_encoding, test_encoding):
    return list(np.linalg.norm(np.array(face_encoding) - np.array(test_encoding), axis=1))
    # axis=1 表示按【行向量】处理


# 定义:人脸比较,输出对应的名称
def comapre_faces_order(face_encoding,test_encoding,names):
    distance = list(np.linalg.norm(np.array(face_encoding) - np.array(test_encoding), axis=1))
    # axis=1 表示按【行向量】处理
    return zip(*sorted(zip(distance,names)))

def main():
    # 2、读取4张图片  【如果文件夹里有很多图片,可以进行遍历】
    img1 = cv2.imread('guo.jpg')
    img2 = cv2.imread('liu1.jpg')
    img3 = cv2.imread('liu2.jpg')
    img4 = cv2.imread('liu3.jpg')
    test = cv2.imread('liu4.jpg')
    # 由 BGR转换为了 RGB.
    img1 = img1[:, :, ::-1]
    img2 = img2[:, :, ::-1]
    img3 = img3[:, :, ::-1]
    img4 = img4[:, :, ::-1]
    test = test[:, :, ::-1]

    img_names = ['guo.jpg','liu1.jpg','liu2.jpg','liu3.jpg','liu4.jpg']


    # 3、加载人脸检测器
    detector = dlib.get_frontal_face_detector()  # 正脸检测

    # 4、加载关键点检测器
    predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

    # 5、加载人脸编码/检测模型
    encoder = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat')

    # 6、调用方法:128维特征向量输出
    img1_128D = encoder_face(img1, detector, predictor, encoder)[0]  # 如果里面有多张人脸,只取第一张人脸的特征向量
    img2_128D = encoder_face(img2, detector, predictor, encoder)[0]
    img3_128D = encoder_face(img3, detector, predictor, encoder)[0]
    img4_128D = encoder_face(img4, detector, predictor, encoder)[0]
    test_128D = encoder_face(test, detector, predictor, encoder)[0]

    four_img_128D = [img1_128D, img2_128D, img3_128D, img4_128D]

    # 7、调用方法:比较特征向量(人脸),计算特征向量之间的距离,判断是否为同一人
    distance = compare_faces(four_img_128D, test_128D)
    print(distance)

    distance,name = comapre_faces_order(four_img_128D,test_128D,img_names)
    print(f"distance:{distance}, \n name:{name}")

if __name__ == '__main__':
    main()
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值