人脸检测
实现请看上一篇文章:我 是 链 接
算法API
在Opencv中,一共有三种自带的识别算法:
Eigenface,FisherFace和LBPH。
#会产生0-20000的可信度评分,一般低于4000-5000都视为不错的识别结果
#Eigenface(特征脸)
cv2.face.EigenFaceRecognizer_create()
#FisherFace(LDA线性判别分析)
cv2.face.FisherFaceRecognizer_create()
#一般高于80都为不可信的识别,低于50都是不错的识别
#LBPH()
cv2.face.LBPHFaceRecognizer_create()
测试例子
face_get.py 用于截取人脸,注意新建目录face_img
#coding=utf-8
import cv2
name = raw_input("Name >")
i = 1
face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
camera = cv2.VideoCapture(0)
while True:
ret, frame = camera.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
#cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
face_img = cv2.resize(gray[y:y+h,x:x+w],(200,200))
print face_img
print '--------------------------'
cv2.imwrite('./face_img/' + name + '-' + str(i) + '.pgm',face_img)
print x,y,w,h
i = i + 1
#cv2.imshow("camera", frame)
#if cv2.waitKey(1000 / 12) & 0xff == ord("q"):
# break
camera.release()
#cv2.destroyAllWindows()
face_eig.py Eigenface算法示例
#coding=utf-8
import os
import cv2
import numpy as np
def load_face(path): #加载人脸数据
X,Y,N = [],[],[]
for r,d,f in os.walk(path):
for file in f:
if file.endswith("pgm"):
img = cv2.imread(path + "/" + file,cv2.IMREAD_GRAYSCALE)
print file
#img = cv2.resize(img,(200,200))
buf = file.split("-")
N.append(buf[0])
X.append(np.asarray(img,dtype=np.uint8))
Y.append(int(buf[1].split(".")[0]))
return X,Y,N #人脸数据数组,ID,名称
def face_eig(path):
[X,Y,N] = load_face(path)
Y = np.asarray(Y,dtype=np.int32) #将ID转为numpy数组,使其与人脸数据一一对应
model = cv2.face.createEigenFaceRecognizer() #加载算法
model.train(np.asarray(X),np.asarray(Y)) #导入数据
face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
camera = cv2.VideoCapture(0)
while True:
ret, frame = camera.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
face = gray[x:x+w,y:y+h] #得到人脸区域
try:
face = cv2.resize(face,(200,200),interpolation=cv2.INTER_LINEAR) #调整尺寸,方便使用Eigenface算法
[id,value] = model.predict(face) #检测,返回上面对应的ID和可信度评分,Eigenface算法会产生0到0-20000 的值,一般低于4000-5000的识别都算是比较精准的
print "ID:",id,"Value:",value,"Name:",N[id]
except:
continue
if __name__ == "__main__":
face_eig("./face_img")