face模块目前支持的算法有:
(1)主成分分析(PCA)——Eigenfaces(特征脸)——函数:createEigenFaceRecognizer()
PCA:低维子空间是使用主元分析找到的,找具有最大方差的哪个轴。
缺点:若变化基于外部(光照),最大方差轴不一定包括鉴别信息,不能实行分类。
(2)线性判别分析(LDA)——Fisherfaces(特征脸)——函数: createFisherFaceRecognizer()
LDA:线性鉴别的特定类投影方法,目标:实现类内方差最小,类间方差最大。
(3)局部二值模式(LBP)——LocalBinary Patterns Histograms——函数:createLBPHFaceRecognizer()
PCA和LDA采用整体方法进行人脸辨别,LBP采用局部特征提取,除此之外,还有的局部特征提取方法为:
import cv2
import os
cam = cv2.VideoCapture(0)
cam.set(3, 640) # 设置图像宽度
cam.set(4, 480) # 设置图像高度
# 人脸检测器
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 每个训练的新人脸需要输入对应的ID
face_id = input('\n 请输入您的ID,按Enter键确认 ==> ')
print("\n [提示] 相机初始化完毕,请看向相机等待采样.......")
# 初始化每次采样图像帧数
count = 0
while(True):
ret, img = cam.read()
#img = cv2.flip(img, -1) # 控制相机图像翻转
img = cv2.flip(img, 1) # 控制相机图像翻转
# 图像灰度化
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
# 将检测到的人脸图像按照一定的命名规则保存到数据集文件夹中
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 # 按ESC退出循环
if k == 27:
break
elif count >= 100: # 采样一百张人脸图像后退出循环
break
# 退出程序
print("\n [提示] 退出程序,清除内存")
cam.release()
cv2.destroyAllWindows()
import cv2
import numpy as np
from PIL import Image
import os
# 人脸数据集的保存路径
path = 'dataset'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
# 获取数据集图像和标签
def getImagesAndLabels(path):
imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
faceSamples=[]
ids = []
for imagePath in imagePaths:
if imagePath == "dataset/.DS_Store":
continue
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)
print(id)
return faceSamples,ids
print ("\n [提示] 开始训练数据集,将耗费一定的时间,请稍后......")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))
# 将训练好的模型保存到路径:trainer/trainer.yml
recognizer.write('trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi
# 打印训练好的人脸个数,退出程序
print("\n [提示] {0} 个人脸已训练完毕,退出程序。".format(len(np.unique(ids))))
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
# 初始化ID
id = 0
# 姓名数组与ID编号相关联,比如ID=1,name=ZhangJunYang
names = ['None', 'ZhangJunYang', 'FanJiangTao', 'LiuJianQing', 'ChengWei', 'W']
# 初始化相机开始采集图像
cam = cv2.VideoCapture(0)
cam.set(3, 640) # 图像宽度设置
cam.set(4, 480) # 图像高度设置
# 定义可以识别人脸的最小窗口尺寸
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)
while True:
ret, img =cam.read()
#img = cv2.flip(img, -1) # 控制图像翻转
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 ,其中 Confidence 值与相似度成反比
id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
if(confidence >= 0 and confidence < 50 ):
id = names[id]+'_sure'
confidence = " {0}%".format(round(100 - confidence))
# Check if confidence is less them 100 ==> "0" is perfect match
elif (confidence >= 50):
id = names[id] +'_maybe'
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)
# 按ESC退出识别程序
k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
if k == 27:
break
print("\n [提示] 清除内存,退出程序")
cam.release()
cv2.destroyAllWindows()