Ubuntu+dlib+opencv摄像头实时人脸识别(含训练人脸库)

Face_Recognition_dlib

环境

  1. Ubuntu 16.04
  2. opencv 3.0 for python3.6 pip install opencv-python
  3. dlib 19.16

模型下载

人脸关键点检测器 predictor_path="shape_predictor_68_face_landmarks.dat
人脸识别模型 face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat
含人脸库candidate-face中人脸不同表情的测试数据集 test-face.zip 解压后与上述文件均置于根目录下
下载地址 : 百度云盘 https://pan.baidu.com/s/1h01sfvf5KWU6_7c2-i5HTQ

运行

运行python candidate_train.py 获得人脸库特征信息,存储在candidates.npycandidates.txt 中 。

candidate_train.py文件:

# -*- coding: UTF-8 -*-

import os,dlib,numpy
import cv2

# 1.人脸关键点检测器
predictor_path = "shape_predictor_68_face_landmarks.dat"

# 2.人脸识别模型
face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat"

# 3.候选人脸文件夹
faces_folder_path = "candidate-face"

# 4.需识别的人脸
img_path = "test-face/0001_IR_allleft.jpg"

# 5.识别结果存放文件夹
faceRect_path = "faceRec"


# 1.加载正脸检测器
detector = dlib.get_frontal_face_detector()

# 2.加载人脸关键点检测器
sp = dlib.shape_predictor(predictor_path)

# 3. 加载人脸识别模型
facerec = dlib.face_recognition_model_v1(face_rec_model_path)



# 候选人脸描述子list

candidates = []

filelist = os.listdir(faces_folder_path)
count = 0
for fn in filelist:
        count = count+1
descriptors = numpy.zeros(shape=(count,128))
n = 0
for file in filelist:
    f = os.path.join(faces_folder_path,file)
    #if os.path.splitext(file)[1] == ".jpg" #文件扩展名
    print("Processing file: {}".format(f))
    img = cv2.imread(f)
    # 1.人脸检测
    dets = detector(img, 1)

    for k, d in enumerate(dets):
        # 2.关键点检测
        shape = sp(img, d)

        # 3.描述子提取,128D向量
        face_descriptor = facerec.compute_face_descriptor(img, shape)
        # 转换为numpy array
        v = numpy.array(face_descriptor)

        descriptors[n] = v

        # descriptors.append(v)
        candidates.append(os.path.splitext(file)[0])

    n += 1

    for d in dets:
        # print("faceRec locate:",d)
        # print(type(d))
        # 使用opencv在原图上画出人脸位置
        left_top = (dlib.rectangle.left(d), dlib.rectangle.top(d))
        right_bottom = (dlib.rectangle.right(d), dlib.rectangle.bottom(d))
        cv2.rectangle(img, left_top, right_bottom, (0, 255, 0), 2)

    # cv2.imwrite(os.path.join(faceRect_path,file), img)

numpy.save('candidates.npy',descriptors)
file= open('candidates.txt', 'w')
for candidate in candidates:
    file.write(candidate)
    file.write('\n')
file.close()

运行 python facerec_68point.py 得到识别结果all-face-result.jpg。

facerec_68point.py文件:

# -*- coding: UTF-8 -*-

import dlib
import cv2
import numpy

# 待检测图片
img_path = "all-face.jpg"
# 人脸关键点检测器
predictor_path="shape_predictor_68_face_landmarks.dat"
# 人脸识别模型
face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat"
# 候选人文件
candidate_npydata_path = "candidates.npy"
candidate_path = "candidates.txt"

# 加载正脸检测器
detector = dlib.get_frontal_face_detector()
# 加载人脸关键点检测器
sp = dlib.shape_predictor(predictor_path)
# 加载人脸识别模型
facerec = dlib.face_recognition_model_v1(face_rec_model_path)


# 候选人脸描述子list

# 读取候选人数据
npy_data=numpy.load(candidate_npydata_path)
descriptors=npy_data.tolist()

# 候选人名单
candidate = []
file=open(candidate_path, 'r')
list_read = file.readlines()
for name in list_read:
    name = name.strip('\n')
    candidate.append(name)

print("Processing file: {}".format(img_path))
img = cv2.imread(img_path)

# 1.人脸检测
dets = detector(img, 1)
print("Number of faces detected: {}".format(len(dets)))



for k, d in enumerate(dets):
    # 2.关键点检测
    shape = sp(img, d)
    face_descriptor = facerec.compute_face_descriptor(img, shape)
    d_test2 = numpy.array(face_descriptor)
    # 计算欧式距离
    dist = []
    for i in descriptors:
        dist_ = numpy.linalg.norm(i - d_test2)
        dist.append(dist_)
    num = dist.index(min(dist))  # 返回最小值

    left_top = (dlib.rectangle.left(d), dlib.rectangle.top(d))
    right_bottom = (dlib.rectangle.right(d), dlib.rectangle.bottom(d))
    cv2.rectangle(img, left_top, right_bottom, (0, 255, 0), 2, cv2.LINE_AA)
    text_point = (dlib.rectangle.left(d), dlib.rectangle.top(d) - 5)
    cv2.putText(img, candidate[num], text_point, cv2.FONT_HERSHEY_PLAIN, 2.0, (255, 255, 255), 2, 1)  # 标出face

cv2.imwrite('all-face-result.jpg', img)

# cv2.imshow("img",img) # 转成BGR显示
#
# cv2.waitKey(0)
# cv2.destroyAllWindows()

运行 this_is_who_camera.py 打开摄像头进行实时的人脸识别

this_is_who_camera.py文件:

# -*- coding: UTF-8 -*-

import dlib,numpy 
import cv2          
import time

# 1.人脸关键点检测器
predictor_path = "shape_predictor_68_face_landmarks.dat"
# 2.人脸识别模型
face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat"
# 3.候选人文件
candidate_npydata_path = "candidates.npy"
candidate_path = "candidates.txt"
# 4.储存截图目录
path_screenshots = "screenShots/"


# 加载正脸检测器
detector = dlib.get_frontal_face_detector()
# 加载人脸关键点检测器
sp = dlib.shape_predictor(predictor_path)
# 加载人脸识别模型
facerec = dlib.face_recognition_model_v1(face_rec_model_path)


# 候选人脸描述子list
# 读取候选人数据
npy_data=numpy.load(candidate_npydata_path)
descriptors=npy_data.tolist()
# 候选人名单
candidate = []
file=open(candidate_path, 'r')
list_read = file.readlines()
for name in list_read:
    name = name.strip('\n')
    candidate.append(name)

# 创建 cv2 摄像头对象
cv2.namedWindow("camera", 1)
cap = cv2.VideoCapture(0)
cap.set(3, 480)
# 截图 screenshots 的计数器
cnt = 0
while (cap.isOpened()):  #isOpened()  检测摄像头是否处于打开状态
    ret, img = cap.read()  #把摄像头获取的图像信息保存之img变量
    if ret == True:       #如果摄像头读取图像成功
        # 添加提示
        cv2.putText(img, "press 'S': screenshot", (20, 400), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1, cv2.LINE_AA)
        cv2.putText(img, "press 'Q': quit", (20, 450), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1, cv2.LINE_AA)

        # img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)
        dets = detector(img, 1)
        if len(dets) != 0:
            # 检测到人脸
            for k, d in enumerate(dets):
                # 关键点检测
                shape = sp(img, d)
                # 遍历所有点圈出来
                for pt in shape.parts():
                    pt_pos = (pt.x, pt.y)
                    cv2.circle(img, pt_pos, 2, (0, 255, 0), 1)
                face_descriptor = facerec.compute_face_descriptor(img, shape)
                d_test2 = numpy.array(face_descriptor)
                # 计算欧式距离
                dist = []
                for i in descriptors:
                    dist_ = numpy.linalg.norm(i - d_test2)
                    dist.append(dist_)
                num = dist.index(min(dist))  # 返回最小值

                left_top = (dlib.rectangle.left(d), dlib.rectangle.top(d))
                right_bottom = (dlib.rectangle.right(d), dlib.rectangle.bottom(d))
                cv2.rectangle(img, left_top, right_bottom, (0, 255, 0), 2, cv2.LINE_AA)
                text_point = (dlib.rectangle.left(d), dlib.rectangle.top(d) - 5)
                cv2.putText(img, candidate[num][0:4], text_point, cv2.FONT_HERSHEY_PLAIN, 2.0, (255, 255, 255), 1, 1)  # 标出face

            cv2.putText(img, "facesNum: " + str(len(dets)), (20, 50),  cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 0), 2, cv2.LINE_AA)
        else:
            # 没有检测到人脸
            cv2.putText(img, "facesNum:0", (20, 50),  cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 0), 2, cv2.LINE_AA)

        k = cv2.waitKey(1)
        # 按下 's' 键保存
        if k == ord('s'):
            cnt += 1
            print(path_screenshots + "screenshot" + "_" + str(cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + ".jpg")
            cv2.imwrite(path_screenshots + "screenshot" + "_" + str(cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + ".jpg", img)

        # 按下 'q' 键退出
        if k == ord('q'):
            break
        cv2.imshow("camera", img)

# 释放摄像头
cap.release()
cv2.destroyAllWindows()

补充

  1. 每次人脸库candidate-face中加入新的人脸数据,均需运行python candidate_train.py
  2. python facerec_68point.py检测的是与人脸库中最相似的
  3. 提供 this_is_who.py 进行在test-face文件夹中的批量测试,测试结果存于faceRec文件夹,识别错误结果存于faceRec_ERROR
  4. 最近的项目是在红外人脸图像上进行的,人脸不太清晰,如果是正常摄像头效果应该会更好

运行结果

python facerec_68point.py在单张上的测试结果:
在这里插入图片描述
this_is_who.py在test-face文件夹中的批量测试结果:
在这里插入图片描述
this_is_who_camera.py实时检测效果.py
在这里插入图片描述
摄像头截图:
在这里插入图片描述
项目地址 :https://github.com/zj19941113/Face_Recognition_dlib

  • 7
    点赞
  • 104
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
人脸识别门禁系统是一种基于人脸识别技术的智能门禁系统,其可通过对人脸进行采集、识别和比对,实现对门禁的控制和管理。本文将详细阐述基于python+openCV+dlib+mysql的人脸识别门禁系统的设计与实现。 一、技术选型 本系统主要采用以下技术: 1. Python:作为主要编程语言,用于实现整个系统的逻辑控制和算法设计。 2. OpenCV:作为图像处理,用于实现人脸检测、特征提取和人脸识别等核心功能。 3. Dlib:作为人脸识别,用于实现人脸特征点检测和人脸识别等功能。 4. MySQL:作为数据系统,用于存储人脸特征和相关信息。 二、系统设计 本系统主要包括以下功能模块: 1. 人脸采集模块:用于采集用户的人脸图像,并将其存储到本地或远程数据中。 2. 人脸检测模块:用于检测人脸区域,提取人脸特征,并将其存储到数据中。 3. 人脸识别模块:用于识别用户的人脸特征,并与数据中的人脸特征进行比对,以确定用户身份。 4. 门禁控制模块:根据用户身份结果,控制门禁的开关。 5. 数据管理模块:用于管理数据中的人脸特征和相关信息。 三、系统实现 1. 人脸采集模块 人脸采集模块主要是通过摄像头对用户的人脸进行拍摄和保存。代码如下: ```python import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() cv2.imshow("capture", frame) if cv2.waitKey(1) & 0xFF == ord('q'): #按q键退出 cv2.imwrite("face.jpg", frame) #保存人脸图像 break cap.release() cv2.destroyAllWindows() ``` 2. 人脸检测模块 人脸检测模块主要是通过OpenCV中的CascadeClassifier类进行人脸检测,再通过Dlib中的shape_predictor类进行人脸特征点检测和特征提取。代码如下: ```python import cv2 import dlib detector = dlib.get_frontal_face_detector() #人脸检测器 predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") #特征点检测器 img = cv2.imread("face.jpg") #读取人脸图像 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转换为灰度图像 faces = detector(gray, 0) #检测人脸 for face in faces: landmarks = predictor(gray, face) #检测特征点 for n in range(68): x = landmarks.part(n).x y = landmarks.part(n).y cv2.circle(img, (x, y), 2, (0, 255, 0), -1) #绘制特征点 cv2.imshow("face", img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 3. 人脸识别模块 人脸识别模块主要是通过Dlib中的face_recognition类进行人脸特征提取和比对。代码如下: ```python import face_recognition known_image = face_recognition.load_image_file("known_face.jpg") #读取已知的人脸图像 unknown_image = face_recognition.load_image_file("unknown_face.jpg") #读取待识别的人脸图像 known_encoding = face_recognition.face_encodings(known_image)[0] #提取已知人脸的特征 unknown_encoding = face_recognition.face_encodings(unknown_image)[0] #提取待识别人脸的特征 results = face_recognition.compare_faces([known_encoding], unknown_encoding) #比对人脸特征 if results[0]: print("Match") else: print("No match") ``` 4. 门禁控制模块 门禁控制模块主要是通过GPIO控制门禁的开关。代码如下: ```python import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) GPIO.output(11, GPIO.HIGH) #开门 time.sleep(5) #等待5秒 GPIO.output(11, GPIO.LOW) #关门 GPIO.cleanup() #清理GPIO资源 ``` 5. 数据管理模块 数据管理模块主要是通过MySQLdb模块实现对MySQL数据的连接和操作,包括新建数据、新建表、插入数据、查询数据等。代码如下: ```python import MySQLdb #连接数据 conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="test", charset="utf8") #新建表 cursor = conn.cursor() sql = "CREATE TABLE `face` (`id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `encoding` text NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;" cursor.execute(sql) #插入数据 name = "张三" encoding = "0.1,0.2,0.3,0.4" sql = "INSERT INTO `face` (`name`, `encoding`) VALUES (%s, %s)" cursor.execute(sql, (name, encoding)) conn.commit() #查询数据 sql = "SELECT * FROM `face` WHERE `name`=%s" cursor.execute(sql, (name,)) result = cursor.fetchone() print(result) cursor.close() conn.close() ``` 四、总结 本文主要介绍了基于python+openCV+dlib+mysql的人脸识别门禁系统的设计与实现。该系统主要采用了Python作为主要编程语言,OpenCVDlib作为图像处理和人脸识别,MySQL作为数据系统。通过对这些技术的应用,实现了人脸采集、检测、识别和门禁控制等核心功能。该系统可以应用于各类场景的门禁控制和身份验证,具有较高的实用价值。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值