人脸识别由人脸检测,特征提取,人脸识别所组成。
1.人脸检测
(1条消息) 用python-opencv实现简单的人脸检测(代码+理论知识)_Yory__的博客-CSDN博客
可以参考这篇博客
2.训练模型
在训练模型中,虽然我们已经安装过opencv的库,但我们直接运行会出现,这样的错误:
AttributeError: module 'cv2' has no attribute 'face'
这是因为我们?cv2.face.LBPHFaceRecognizer_create()所用的是opencv的辅助face库,我们的解决方法是在终端中输入
pip install opencv-contrib-python
完成后,先在文件夹中创建需要训练的图片,按顺序依次排序。编写代码:
import cv2
import os
import sys
from PIL import Image
import numpy as np
def getImageAndLabels(path):
facesSamples=[]
ids=[]
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
# 检测人脸
face_detector = cv2.CascadeClassifier('D:\\2\\haarcascade_frontalface_alt.xml')
# 遍历列表中的图片
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L')
# 将图像转换为数组
img_numpy = np.array(PIL_img,'uint8')
faces = face_detector.detectMultiScale(img_numpy)
# 获取每张图片的id
print(os.path.split(imagePath))
id = int(os.path.split(imagePath)[1].split('.')[0]) # 将图片和路径分类并获得
# 将获取的图片和id添加到list中
for x,y,w,h in faces:
facesSamples.append(img_numpy[y:y+h,x:x+w])
ids.append(id)
return facesSamples,ids
if __name__== '__main__':
#图片路径
path = 'D:/2/.pictures/'
faces,ids=getImageAndLabels(path)
#获取循环对象
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces,np.array(ids))
#保存文件
recognizer.write('train/trainer.yml')
?完成该项后会在文件夹中产生trainer.yml
?3.人脸识别代码
在代码中有详尽的解释
import cv2
import numpy as np
import os
names = ['','MM','MM','MM','MM','MM','Jay','Jay','Jay','Jay','Jay',]
recognizer = cv2.face.LBPHFaceRecognizer_create() # 识别的方法
recognizer.read('train/trainer.yml') # 用于识别的训练模型
img = cv2.imread('D:/2/jm.jpg') # 准备识别的图片
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
face_detector = cv2.CascadeClassifier("D:\\2\\haarcascade_frontalface_alt.xml") # 再次调用人脸分类器
faces = face_detector.detectMultiScale(gray,minNeighbors=30) # 识别人脸
# 校验
font = cv2.FONT_HERSHEY_SIMPLEX # 字体
for x,y,w,h in faces:
id, confidence = recognizer.predict(gray[y:y + h, x:x + w]) # 获取人脸宽度与高度
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
cv2.putText(img,str(round(100-confidence))+ "%",(x+5,y+h-5),font,2,(255,0,0),2)
# 添加一个检验的过程
if confidence < 100:
name = names[id]
confidence = round(100-confidence) # 四舍五入
else:
name = "unknown"
confidence = round(100-confidence)
cv2.putText(img,name,(x,y),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,0),2)
print("可信度",confidence,"%")
cv2.imshow('recogonize',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|