用Dlib进行简单的人脸特征提取特征向量到CSV文件中,用KNN进行预测识别

目标要求:基于收集的全班人脸数据实现分类识别,要求基于图片进行比对识别

任务流程大致分为以下过程:

1)模型准备:下载并部署一个人脸特征提取模型(功能包括人脸检测、人脸特征提取,不限算法,比如dlib. paddlehub等)

需要的准备好的Dlib两个模型为

dlib_face_recognition_resnet_model_v1.dat

shape_predictor_68_face_landmarks.dat

进行人脸检测和标注68个特征点

import numpy as np
import cv2
import dlib 
detector=dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('dlib\shape_predictor_68_face_landmarks.dat')
# cv2读取图像
img = cv2.imread("D:\\postSchool\\Project\\face_recognition\\34class_face_dataset\\dlrb.png")
#print(img)
# 取灰度
img_gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
# 人脸数rects
rects = detector(img_gray, 1)
print(rects)
for i in range(len(rects)):
    landmarks = np.matrix([[p.x, p.y] for p in predictor(img,rects[i]).parts()])
    for idx, point in enumerate(landmarks):
        # 68点的坐标
        pos = (point[0, 0], point[0, 1])
        print(idx,pos)
        # 利用cv2.circle给每个特征点画一个圈,共68个
        cv2.circle(img, pos, 5, color=(0, 255, 0))
        # 利用cv2.putText输出1-68
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img, str(idx+1), pos, font, 0.8, (0, 0, 255), 1,cv2.LINE_AA)
cv2.namedWindow("img", 2)
cv2.imshow("img", img)
cv2.waitKey(0)

 

 

 

2)人脸特征值数据提取并保存:dib模型68个特征点对 应中人脸特征值为1个128维度向量,将特征值合并保存为csv文件

我的文件数据下有68张图片:

 

import cv2
import os
import dlib
from skimage import io
import csv
import numpy as np

# 要读取人脸图像文件的路径
path_images_from_our = "D:\\postSchool\\Project\\face_recognition\\34class_face_dataset\\"
# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# Dlib 人脸预测器
predictor = dlib.shape_predictor("dlib\shape_predictor_68_face_landmarks.dat")
# Dlib 人脸识别模型,将人脸映射成128D矢量
face_rec = dlib.face_recognition_model_v1("dlib\dlib_face_recognition_resnet_model_v1.dat")


# 返回单张图像的 128D 特征
def return_128d_features(path_img):
    img_rd = io.imread(path_img)
    img_gray = cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB)
    faces = detector(img_gray, 1)
    print("%-40s %-20s" % ("正在处理的人脸图像 / image with faces detected:", path_img), '\n')
    # 确保检测到是人脸图像去算特征
    if len(faces) != 0:
        shape = predictor(img_gray, faces[0])
        face_descriptor = face_rec.compute_face_descriptor(img_gray, shape)
    else:
        face_descriptor = 0
        print("no face")
    return face_descriptor

# 读取每个人人脸图像的数据
people = os.listdir(path_images_from_our)
os.listdir()
print(people)
with open("D:\\postSchool\\Project\\face_recognition\\face_features\\features_all.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    for person in people:
    #for i in range(0,2):
        print("******" + person + "****** Processing")
        features_128d = return_128d_features(path_images_from_our + "/" + person)
        print("特征值 / The features:", list(features_128d))
        writer.writerow(features_128d)#按行写入到Csv文件中
        print('\n')
    print("3,4班的人脸数据存入 / Save all the features of faces registered into: D:\\postSchool\\Project\\face_recognition\\34class_face_dataset\\features_all.csv.csv")

 

 

    生成的CSV文件的维度为  68X128(每一行为每个人的128个特征向量)
3)人脸分类knn模型训练:基于生成的csx文件数据,构建knn算法并进行训练,该算法邻居数为1

   ps:我这里因为在处理图片的时候没有将对应图片的标签给读进去,所以自己手动补了68份Target标签(有点蠢哈哈)

import sklearn.datasets as datasets  # 导入数据库
from sklearn.neighbors import KNeighborsClassifier  # 导入KNN分类算法
import numpy as np
import pandas as pd
data = pd.read_csv("D:\\postSchool\\Project\\face_recognition\\face_features\\features_all.csv",header=None)
# 提取样本数据
data['target']=[3301,3302,3303,3304,3305,3307,3308,3309,3310,
       3311,3312,3313,3314,3315,3316,3317,3318,
       3319,3320,3321,3322,3323,3324,3325,3326,3327,3328,3329, 
       3330,3331,3332,3333,3334,3401,3402, 
       3403,3404,3405,3406,3407,3408,3409, 
       3410,3411,3412,3413,3414,3415,3416, 
       3417,3418,3419,3420,3421,3422,3423, 
       3424,3425,3426,3427,3428,3429,3430, 
       3431,3432,3433,3434,3435]  #手动加入标签
feature = data.iloc[:,:128]  # 特征数据
target=data['target']#标签数据
feature.head(5) #查看数据
target.head(5)
# 训练模型对象
knn = KNeighborsClassifier(n_neighbors=1)  
knn_face = knn.fit(feature, target)
print(knn_face)  # 打印训练的结果
# 预测分类结果的评分
print("KNN Score:",knn.score(feature,target))


4) 数据预测:待预测图像进行人脸特征值提取, 用KNN模型进行预测,并输出分类。
      因为这里数据集很少,每个人只有一次特征提取,所以直接用KNN进行预测,将新预测的图片也用人脸特征提取,然后用KNN计算与之最相近的特征,进行分类判断

#进行预测
test_path_img='D:\\postSchool\\Project\\face_recognition\\34class_face_dataset\\3419.png'#已知学号为3419
test_one=return_128d_features(test_path_img)#测试预测一张图片,转换成特征向量
X=np.array(test_one)
X=X.reshape(1, -1)#转变成一行数组
Y_lable = knn.predict(X)
print("预测该学号为:",Y_lable)

 结语:

        在完成这些的时候,Dlib库的安装碰了壁,我参考的是

        dlib 安装教程(三种方法)_MuMengSunny的博客-CSDN博客_dlib库安装

        我使用第三种安装方法,才成功安装,还有用openCV的时候打开图片路径一定不要有中文,最好使用\\+绝对路径

需要模型的自取

链接: https://pan.baidu.com/s/10DBM8aEy8ziDAT-ufQi71g 提取码: x4vs 复制这段内容后打开百度网盘手机App,操作更方便哦

参考资料 :

1.Dlib模型实现人脸识别_HarrietLH的博客-CSDN博客

2. dlib 安装教程(三种方法)_MuMengSunny的博客-CSDN博客_dlib库安装

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值