python 基于face_recognition的人脸识别(1)

python人脸识别(1)

现在使用的是face_recognition库
我们的人脸识别基于face_recognition库。face_recognition基于dlib实现,用深度学习训练数据,模型准确率高达99.38%。

  1. 安装 python3
    百度搜索python下载安装即可。下载地址https://www.python.org/downloads/windows/
    安装完输入python出现版本号安装成功在这里插入图片描述
  2. 安装pytohn 的opencv库
    如果获取视频要用到opencv库
    pip install opencv-python 安装
    安装完import cv2 测试是否安装成功在这里插入图片描述
  3. 安装dlib库
    face_recognition人脸识别是基于dlib实现的,也可以直接用dlib实现人脸识别(以后会说)。
    Dlib是一个包含机器学习算法的C++开源工具包。Dlib可以帮助您创建很多复杂的机器学习方面的软件来帮助解决实际问题。目前Dlib已经被广泛的用在行业和学术领域,包括机器人,嵌入式设备,移动电话和大型高性能计算环境。Dlib是开源的、免费的;官网和git地址:#官网http://dlib.net/#githubhttps://github.com/davisking/dlibDlib
    可以下载未编译的,自己编译,可以开启显卡运行识别,速度会有提升,得有vs与cmake;也可直接下载python对应版本的。
    下载地址https://pypi.org/project/dlib/。
    下载与python对应版本的dlib库后 pip install 下载的dlib 安装
  4. 安装 face_recognition库
    pip install face_recognition安装
    安装过程如果网络超时重新安装即可
  5. 官方示例代码
    https://github.com/ageitgey/face_recognition#face-recognition
    下载官方实例代码
    下面是我自己修改的代码,我首先把人脸的 信息加入mysql数据库,方便以后对比识别,需要安装pymysql,pip install pymysql

加入数据库代码

import pymysql.cursors
import face_recognition
import os

# 连接MySQL数据库
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='face', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

#通过cursor创建游标
cursor = connection.cursor()
rootdir = 'E:\\'#照片路径
list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
    path = os.path.join(rootdir,list[i])
    if path.endswith('.jpg') or path.endswith('.png') or path.endswith('.bmp') or path.endswith('.JPG'):
        image = face_recognition.load_image_file(path)
        face_encoding = face_recognition.face_encodings(image)[0]
        # 创建sql 语句,并执行
        sql = "INSERT INTO `face` (`user_name`, `encoding`) VALUES ('{}', '{}')".format(list[i],face_encoding)
        print(sql)
        cursor.execute(sql)
        # 提交SQL
        connection.commit()
connection.close()

实时识别代码

获取存入数据库的人脸,进行实时对比识别

import face_recognition
import cv2
import os
import datetime
import time
import pymysql.cursors
# 创建数组的编码和他们的名字
known_face_encodings = []
known_face_names = []

# 连接MySQL数据库
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='face', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

# 通过cursor创建游标
cursor = connection.cursor()
sql="select user_name,encoding from face1"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
    uname = row['user_name']
    encod = list(map(float,row['encoding'].replace('[','').replace(']','').replace('\n','').split()))
    known_face_names.append(uname)
    known_face_encodings.append(encod)
    print('add'+uname)
connection.close()

#video_capture = cv2.VideoCapture(0)

while True:
    # Grab a single frame of video 抓住一个帧的视频
    ret, frame = video_capture.read()
    #print('读取')
    if frame is None:
        #video_capture = cv2.VideoCapture(0)
        print('丢失帧')
    else:
        rgb_frame = frame[:, :, ::-1]
        # 找到所有的脸和脸enqcodings帧的视频
        face_locations = face_recognition.face_locations(rgb_frame)
        face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
        # 遍历每个面在这个帧的视频
        for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
	    # 看看脸是已知的匹配(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding,0.4)
            name = "Unknown"
            if True in matches:
                first_match_index = matches.index(True)
                name = known_face_names[first_match_index]         
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
			# 下面画一个标签和一个名字
	        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
	        font = cv2.FONT_HERSHEY_DUPLEX
	        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
	        cv2.imshow('Video', frame)
    # 点击键盘上的“q”退出!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#  释放使用的摄像头
video_capture.release()
cv2.destroyAllWindows()

代码中换行与缩进可能有问题需注意

 matches = face_recognition.compare_faces(known_face_encodings, face_encoding,0.4)

其中0.4阈值控制识别精度,默认为0.6,值越小识别的精确度越高:0.35精度大于0.4,如果使用默认0.6识别是不准确的。
此代码实时显示的话速度还需改进(以后会说)

结束

猜你喜欢

转载自blog.csdn.net/zx1x2x3mg/article/details/85014485