Python使用opencv人脸识别

本人小白一枚

 

先把所需要的东西安装上

第三方库:

opencv-python; opencv-contrib-python; PIL; numpy

然后就是人脸的模型:https://github.com/lucas8264/opencv/tree/master/data


↓训练模型的代码(需要在程序根目录创建一个sample文件夹跟trainner文件夹
 1 #!/usr/bin/python3
 2 # -*- coding: utf-8 -*-
 3 # @Time : 2020/9/14 8:51
 4 # @Author : Zero
 5 # @FileName: Face_Trainner.py
 6 # @Software: PyCharm
 7 # @Blog : https://www.cnblogs.com/ZeroZN/
 8 
 9 # 所需第三方库:opencv-python; opencv-contrib-python; PIL; numpy
10 # 必备文件:人脸模型;
11 
12 import cv2, numpy as np, os
13 from PIL import Image
14 
15 # 人脸样本获取
16 def Sample(id):
17     camera = cv2.VideoCapture(0)  # 视频捕获(调用摄像头)
18     # 级联分类器
19     faceDetect = cv2.CascadeClassifier("./haarcascades/haarcascade_frontalface_default.xml")
20     # 样本数量
21     sampleNum = 0
22 
23     while sampleNum != 50: # 获取50张样本后训练模型
24         ret, frame = camera.read()
25         gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
26         faces = faceDetect.detectMultiScale(gray, 1.3, 5)
27         for (x,y,w,h) in faces:
28             sampleNum += 1
29             # 识别到的人脸画框并保存到sample文件夹内
30             cv2.imwrite("sample/User."+str(id)+'.'+str(sampleNum)+'.jpg', gray[y:y+h,x:x+w])
31             cv2.rectangle(frame, (x,y), (x+w,y+h), (212,71,243),2)
32         cv2.imshow('get_sample',frame)
33         cv2.waitKey(1)  # 窗口手动关闭
34     # 释放资源
35     camera.release()
36     cv2.destroyAllWindows()
37 
38 # 训练模型
39 def trainner(path):
40     imagePaths = [os.path.join(path, f) for f in os.listdir(path)]  # 样本位置获取与遍历
41     faces = []
42     IDs = []
43     for imagePath in imagePaths:
44         faceImg = Image.open(imagePath).convert('L')    # 打开为灰度图像
45         faceNp = np.array(faceImg, 'uint8')
46         ID = int(os.path.split(imagePath)[-1].split('.')[1])
47         faces.append(faceNp)
48         print(ID)
49         IDs.append(ID)
50     return IDs, faces
51 
52 if __name__ == '__main__':
53     Sample(input("Enter you Id:"))
54     Ids,faces = trainner('sample')
55     recognizer = cv2.face.LBPHFaceRecognizer_create()   # 人脸识别器
56     recognizer.train(faces, np.array(Ids))  # 训练
57     recognizer.save('trainner/trainner.yml')    # 模型保存位置
View Code

↓人脸识别(只用了opencv

 1 #!/usr/bin/python3
 2 # -*- coding: utf-8 -*-
 3 # @Time : 2020/9/14 9:12
 4 # @Author : Zero
 5 # @FileName: Face_Match.py
 6 # @Software: PyCharm
 7 # @Blog : https://www.cnblogs.com/ZeroZN/
 8 
 9 # 所需第三方库:opencv-python; opencv-contrib-python
10 # 必备文件:人脸模型; 自己训练好的模型
11 
12 import cv2
13 
14 camera = cv2.VideoCapture(0)
15 
16 recognizer = cv2.face.LBPHFaceRecognizer_create()
17 recognizer.read("trainner/trainner.yml")    # 读取训练好的模型
18 faceDetect = cv2.CascadeClassifier("./haarcascades/haarcascade_frontalface_default.xml")
19 font = cv2.FONT_HERSHEY_SIMPLEX # 字体
20 
21 idnum = 0
22 names = ['Zero', 'Alien']    # 名字自己设置
23 
24 while True:
25     ret, frame = camera.read()
26     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
27     faces = faceDetect.detectMultiScale(gray, 1.3, 5)
28     for (x,y,w,h) in faces:
29         cv2.rectangle(frame, (x,y), (x+w, y+h), (212,71,233), 2)
30         idnum, conf = recognizer.predict(gray[y:y+h,x:x+w])
31         if conf < 100:
32             idnum = names[idnum]
33             conf = '{0}%'.format(round(100-conf))
34 
35         else:
36             idnum = 'unknown'
37             conf = '{0}%'.format(round(100-conf))
38         # 窗口放入字体
39         cv2.putText(frame, str(idnum), (x+5, y-5), font, 1, (255,255,255), 1)
40         cv2.putText(frame, str(conf), (x+5, y+h-5), font, 1, (255,255,255), 1)
41 
42     cv2.imshow('Face_Recognition', frame)
43     if cv2.waitKey(1) & 0xff == 27: break
44 
45 camera.release()
46 cv2.destroyAllWindows()
View Code

注:训练模型的时候样本ID跟你后面识别显示出来的名字有关,如果要测试建议用图片测试。

posted @ 2020-09-15 09:36  ZeroZN  阅读(248)  评论(0)    收藏  举报