本文我将如何在树莓派上,使用 OpenCV 和 Python 完成人脸检测项目。不仅可以实时的检测,还可以进行学习、训练和检测。

项目所需设备

硬件:

树莓派4b
树莓派摄像头模块(Camrea V2)

语言和库:

OpenCV
Python 3

环境配置在我上篇博客已经介绍的很详细了,可以进行参考一下。

首先启动树莓派摄像头模块。

 运行树莓派配置工具来激活摄像头模块:

接下来开始项目开始了

本教程使用 OpenCV 完成,一个神奇的「开源计算机视觉库」,并主要关注树莓派(因此,操作系统是树莓派系统)和 Python,但是我也在 Mac 电脑上测试了代码,同样运行很好。OpenCV 具备很强的计算效率,且专门用于实时应用。因此,它非常适合使用摄像头的实时人脸识别。要创建完整的人脸识别项目,我们必须完成3个阶段:

1)人脸检测和数据收集;
2)训练识别器;
3)人脸识别。

一.我们项目的第一步是创建一个简单的数据集,该数据集将储存每张人脸的 ID 和一组用于人脸检测的灰度图。

因此,以下命令行将为我们的项目创建一个目录,目录名可以如以下为 FaceProject 

mkdir FaceProject

在该目录中,除了我们为项目创建的 3 个 Python 脚本外,我们还需要储存人脸分类器。我们可以从 GitHub 中下载:haarcascade_frontalface_default.xml

下一步需要创建一个子目录「dtatset」,并用它来储存人脸样本:

mkdir dataset

收集数据的代码如下:face_dataset_01.py

 1 import cv2
 2 import os
 3  
 4 cam = cv2.VideoCapture(0)
 5 cam.set(3, 640) # set video width
 6 cam.set(4, 480) # set video height
 7  
 8 face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
 9  
10 # For each person, enter one numeric face id
11 face_id = input('\n enter user id end press <return> ==>  ')
12  
13 print("\n [INFO] Initializing face capture. Look the camera and wait ...")
14 # Initialize individual sampling face count
15 count = 0
16  
17 while(True):
18     ret, img = cam.read()
19     img = cv2.flip(img, -1) # flip video image vertically
20     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
21     faces = face_detector.detectMultiScale(gray, 1.3, 5)
22  
23     for (x,y,w,h) in faces:
24         cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
25         count += 1
26  
27         # Save the captured image into the datasets folder
28         cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
29  
30         cv2.imshow('image', img)
31  
32     k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video
33     if k == 27:
34         break
35     elif count >= 30: # Take 30 face sample and stop video
36          break
37  
38 # Do a bit of cleanup
39 print("\n [INFO] Exiting Program and cleanup stuff")
40 cam.release()
41 cv2.destroyAllWindows()

运行命令:python face_dataset_01.py

我是以第一个人的ID唯一开始的,收集测试人的30张灰度图片,存到dataset文件中,可以自己进行查看。

在我的代码中,我从每一个 ID 捕捉 30 个样本,我们能在最后一个条件语句中修改抽取的样本数。如果我们希望识别新的用户或修改已存在用户的相片,可以自己进行添加。

二.开始训练数据

下面开始创建子目录以储存训练数据:

mkdir trainer

在第二阶段中,我们需要从数据集中抽取所有的用户数据,并训练 OpenCV 识别器,这一过程可由特定的 OpenCV 函数直接完成。这一步将在「trainer/」目录中保存为trainer.yml 文件。

训练代码:face_training_02.py

1 import numpy as np
 2 from PIL import Image
 3 import os
 4  
 5 # Path for face image database
 6 path = 'dataset'
 7  
 8 recognizer = cv2.face.LBPHFaceRecognizer_create()
 9 detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
10  
11 # function to get the images and label data
12 def getImagesAndLabels(path):
13     imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
14     faceSamples=[]
15     ids = []
16     for imagePath in imagePaths:
17         PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
18         img_numpy = np.array(PIL_img,'uint8')
19         id = int(os.path.split(imagePath)[-1].split(".")[1])
20         faces = detector.detectMultiScale(img_numpy)
21         for (x,y,w,h) in faces:
22             faceSamples.append(img_numpy[y:y+h,x:x+w])
23             ids.append(id)
24     return faceSamples,ids
25  
26 print ("\n [INFO] Training faces. It will take a few seconds. Wait ...")
27 faces,ids = getImagesAndLabels(path)
28 recognizer.train(faces, np.array(ids))
29  
30 # Save the model into trainer/trainer.yml
31 recognizer.write('trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi
32  
33 # Print the numer of faces trained and end program
34 print("\n [INFO] {0} faces trained. Exiting Program".format(len(np.unique(ids))))

 运行命令:python face_training_02.py 

数据在被训练之后,文件「trainer.yml」将保存在我们前面定义的 trainer 目录下

三.人脸识别

 我们将通过摄像头捕捉一个新人脸,如果这个人的面孔之前被捕捉和训练过,我们的识别器将会返回其预测的 id 和索引。

代码如下:face_recognition_03.py

1 import cv2
 2 import numpy as np
 3 import os 
 4  
 5 recognizer = cv2.face.LBPHFaceRecognizer_create()
 6 recognizer.read('trainer/trainer.yml')
 7 cascadePath = "haarcascade_frontalface_default.xml"
 8 faceCascade = cv2.CascadeClassifier(cascadePath);
 9  
10 font = cv2.FONT_HERSHEY_SIMPLEX
11  
12 #iniciate id counter
13 id = 0
14  
15 # names related to ids: example ==> Marcelo: id=1,  etc
16 names = ['None', 'tanshengjang', 'Paula', 'Ilza', 'Z', 'W'] 
17  
18 # Initialize and start realtime video capture
19 cam = cv2.VideoCapture(0)
20 cam.set(3, 640) # set video widht
21 cam.set(4, 480) # set video height
22  
23 # Define min window size to be recognized as a face
24 minW = 0.1*cam.get(3)
25 minH = 0.1*cam.get(4)
26  
27 while True:
28     ret, img =cam.read()
29     img = cv2.flip(img, -1) # Flip vertically
30     gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
31      
32     faces = faceCascade.detectMultiScale( 
33         gray,
34         scaleFactor = 1.2,
35         minNeighbors = 5,
36         minSize = (int(minW), int(minH)),
37        )
38  
39     for(x,y,w,h) in faces:
40         cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
41         id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
42  
43         # Check if confidence is less them 100 ==> "0" is perfect match 
44         if (confidence < 100):
45             id = names[id]
46             confidence = "  {0}%".format(round(100 - confidence))
47         else:
48             id = "unknown"
49             confidence = "  {0}%".format(round(100 - confidence))
50          
51         cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
52         cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)  
53      
54     cv2.imshow('camera',img) 
55  
56     k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
57     if k == 27:
58         break
59  
60 # Do a bit of cleanup
61 print("\n [INFO] Exiting Program and cleanup stuff")
62 cam.release()
63 cv2.destroyAllWindows()

运行命令:face_recognition_03.py

这里我们包含了一个新数组,因此我们将会展示「名称」,而不是编号的 id:

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

所以,如上所示的列表,tanshengjiang的 ID 或索引为 1,Paula 的 ID 等于 2。
可以自行改成自己的名字或者想要的标记。
到这里,项目基本完成了,好好去跑一遍吧,还挺好玩的。
原文链接:https://shumeipai.nxez.com/2018/03/09/real-time-face-recognition-an-end-to-end-project-with-raspberry-pi.html