用树莓派3B+和Python+OpenCV实现人脸识别

(简单易学,新手友好,小白请进,建议收藏)

使用的硬件设备:树莓派3B+,摄像头,电脑显示器,鼠标,键盘

使用的软件设施:Python3,OpenCV3.4.3

续上一篇博客:https://blog.csdn.net/qiuzitao/article/details/108527366

上一篇讲的是人脸检测,也是人脸识别的基础,接下来这篇我们讲人脸识别

在这里插入图片描述

一、人脸数据采集

我们这个项目的第一步是创建一个简单的数据集,该数据集将储存每张人脸的 ID 和一组用于人脸检测的灰度图。
在这里插入图片描述
在树莓派终端为我们的项目创建一个目录(文件夹),目录名可以如以下为 FacialRecognitionProject 或其它:

mkdir FacialRecognitionProject

这个目录下要放三个py文件和人脸分类器,人脸检测分类器在我们上一篇文章有,传送门在文章开头。

然后我们需要创建一个子目录「dataset」,并用它来储存人脸样本:

mkdir dataset

接下来是三个py文件的第一个,用来存储我们的人脸数据的。

face_dataset.py

import cv2
import os
 
cam = cv2.VideoCapture(0)
cam.set(3, 640) # set video width
cam.set(4, 480) # set video height
 
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
 
# For each person, enter one numeric face id
face_id = input('\n enter user id end press <return> ==>  ')
 
print("\n [INFO] Initializing face capture. Look the camera and wait ...")
# Initialize individual sampling face count
count = 0
 
while(True):
    ret, img = cam.read()
    img = cv2.flip(img, -1) # flip video image vertically
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_detector.detectMultiScale(gray, 1.3, 5)
 
    for (x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
        count += 1
 
        # Save the captured image into the datasets folder
        cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
 
        cv2.imshow('image', img)
 
    k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video
    if k == 27:
        break
    elif count >= 30: # Take 30 face sample and stop video
         break
 
# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()

代码参数解析:

上述的代码和人脸检测的代码非常像,我们只是添加了一个「input command」来接收用户 ID(整数)。

face_id = input('\n enter user id end press  ==>  ')

当你运行之后你就可以输入用户ID比如第一个人你给他个ID是1你就输入1。

cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])

对于捕捉到你头像的每一帧图片,我们保存在「dataset」目录中,对于保存上述文件,我们需要导入「os」库,每一个文件的名字都服从以下结构:User.face_id.count.jpg

例如,对于 face_id = 1 的用户,dataset/ 目录下的第四个样本文件名可能为:User.1.4.jpg

在这里插入图片描述
在我的代码中,我从每一个 ID 捕捉 30 个样本,我们能在最后一个条件语句中修改抽取的样本数。如果我们希望识别新的用户或修改已存在用户的相片,我们就必须以上脚本。

二、训练

这是FacialRecognitionProject文件夹下的第二个我们要创建的py:face_training.py ,我们需要从数据集中抽取所有的用户数据,并训练 OpenCV 识别器,这一过程可由特定的 OpenCV 函数直接完成。这一步将在「trainer/」目录中保存为.yml 文件。
在这里插入图片描述
先创建一个文件夹用来存储训练数据

mkdir trainer

face_training.py

import numpy as np
from PIL import Image
import os
 
# Path for face image database
path = 'dataset'
 
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
 
# function to get the images and label data
def getImagesAndLabels(path):
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
    faceSamples=[]
    ids = []
    for imagePath in imagePaths:
        PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
        img_numpy = np.array(PIL_img,'uint8')
        id = int(os.path.split(imagePath)[-1].split(".")[1])
        faces = detector.detectMultiScale(img_numpy)
        for (x,y,w,h) in faces:
            faceSamples.append(img_numpy[y:y+h,x:x+w])
            ids.append(id)
    return faceSamples,ids
 
print ("\n [INFO] Training faces. It will take a few seconds. Wait ...")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))
 
# Save the model into trainer/trainer.yml
recognizer.write('trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi
 
# Print the numer of faces trained and end program
print("\n [INFO] {0} faces trained. Exiting Program".format(len(np.unique(ids))))

你要在树莓派中已经安装了 PIL 库,如果没有的话,在终端运行以下命令:pip install pillow,如果有提示缺少什么包或者库之类的no model named xxx,你就自己去安装下载pip install xxx。

代码参数解析:

我们将使用 LBPH(LOCAL BINARY PATTERNS HISTOGRAMS)人脸识别器,它由 OpenCV 提供:

recognizer = cv2.face.LBPHFaceRecognizer_create()

函数「getImagesAndLabels (path)」将抽取所有在目录「dataset/」中的照片,并返回 2 个数组:「Ids」和「faces」。通过将这些数组作为输入,我们就可以训练识别器。

recognizer.train(faces, ids)

在训练过后,文件「trainer.yml」将保存在我们前面定义的 trainer 目录下。此外,我们还在最后使用了 print 函数以确认已经训练的用户面部数量。

三、预测

这是该项目的最后阶段,也是我们 FacialRecognitionProject 下要创建的第三个py文face_recognition.py 。这里,我们将通过摄像头捕捉一个人脸,如果这个人的面孔之前被捕捉和训练过,我们的识别器将会返回其预测的 id 和索引,并展示置信度(准确率)。
在这里插入图片描述

face_recognition.py

import cv2
import numpy as np
import os 
 
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
 
font = cv2.FONT_HERSHEY_SIMPLEX
 
#iniciate id counter
id = 0
 
# names related to ids: example ==> Marcelo: id=1,  etc
names = ['None', 'Marcelo', 'Paula', 'Ilza', 'Z', 'W'] 
 
# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)
cam.set(3, 640) # set video widht
cam.set(4, 480) # set video height
 
# Define min window size to be recognized as a face
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)
 
while True:
    ret, img =cam.read()
    img = cv2.flip(img, -1) # Flip vertically
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
     
    faces = faceCascade.detectMultiScale( 
        gray,
        scaleFactor = 1.2,
        minNeighbors = 5,
        minSize = (int(minW), int(minH)),
       )
 
    for(x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
        id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
 
        # Check if confidence is less them 100 ==> "0" is perfect match 
        if (confidence < 100):
            id = names[id]
            confidence = "  {0}%".format(round(100 - confidence))
        else:
            id = "unknown"
            confidence = "  {0}%".format(round(100 - confidence))
         
        cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
        cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)  
     
    cv2.imshow('camera',img) 
 
    k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
    if k == 27:
        break
 
# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()

运行这个 face_recognition.py 后就可以看到我们的项目结果啦。

代码解析:

这里我们包含了一个新数组,因此我们将会展示「名称」(需要英文名字,中文的需要改编码),而不是编号的 id:

names = ['None', 'Marcelo', 'Paula', 'Ilza', 'Z', 'W']

所以,如上所示的列表,Marcelo 的 ID 或索引为 1,Paula 的 ID 等于 2。

下一步,我们将检测一张人脸,正如我们在之前的 haasCascade 分类器中所做的那样。

id, confidence = recognizer.predict(gray portion of the face)

recognizer.predict () 将把待分析人脸的已捕捉部分作为一个参数,并返回其可能的所有者,指示其 id 以及识别器与这一匹配相关的置信度。
注意,如果匹配是完美的,置信度指数将返回「零」。

最后,如果识别器可以预测人脸,我们将在图像上放置一个文本,带有可能的 id,以及匹配是否正确的概率(概率=100 – 置信度指数)。如果没有,则把“未知”的标签放在人脸上。

图源:树莓派实验室

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiuzitao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值