python opencv人脸识别

Python OpenCV 人脸识别

局部二值模式直方图人脸识别器

从图像中提取出局部特征,用LBP这种方式提取出的特征具有较低的维度。会发现图像的表达不受光照变化的影响。局部二值模式的基本思想是通过比较像素和它的邻域归纳出图像的局部构成。

以一个像素为中心,与其邻域进行比较。如果中心像素的灰度值大于它的邻域,则将其赋值为1,否则为0.由此,每一个像素点最终会得到一个二进制数,例如11001111。因此,一个8邻域的像素,最终会有2^8种组合,叫做局部二值模式。

import cv2 as cv
import os
import numpy as np
import sklearn.preprocessing as sp

fd = cv.CascadeClassifier('face.xml')
def search_faces(directory):
    directory = os.path.normpath(directory)
    if not os.path.isdir(directory):
        raise IOError("目录不存在:"+ directory)
    faces = {}
    for curdir,subdirs,files in os.walk(directory): #遍历目录
        for jpeg in (file for file in files if file.endswith('.jpg')):
            path = os.path.join(curdir,jpeg)
            label = path.split(os.path.sep)[-2]#获得图片当前目录名称
            if label not in faces:
                faces[label] = []
            faces[label].append(path)
    return faces
train_faces = search_faces('faces/objects/training')
codec = sp.LabelEncoder()#标签编码器
codec.fit(list(train_faces.keys()))#转换为编码字典
train_x,train_y = [],[]
for label,filenames in train_faces.items():
    for filename in filenames:
        image = cv.imread(filename)
        gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
        #比minSize(像素)还小的尺寸,忽略。
        faces = fd.detectMultiScale(gray,1.1,3,minSize=(100,100)) #定位脸部
        for l,t,w,h in faces:
            train_x.append(gray[t:t+h,l:l+w])#外切脸部
            train_y.append(codec.transform([label])[0])
train_y = np.array(train_y)
model = cv.face.LBPHFaceRecognizer_create()#局部二值模式直方图人脸识别器
model.train(train_x,train_y)#训练模型
#以下模型测试/预测
test_faces = search_faces('faces/objects/testing')
test_x,test_y,test_img = [],[],[]
for label,filenames in test_faces.items():
    for filename in filenames:
        image = cv.imread(filename)
        gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
        #比minSize(像素)还小的尺寸,忽略。
        faces = fd.detectMultiScale(gray,1.1,2,minSize=(100,100)) #定位脸部
        for l,t,w,h in faces:
            test_x.append(gray[t:t+h,l:l+w])#外切脸部
            test_y.append(codec.transform([label])[0])
            a,b = int(w/2),int(h/2)
            cv.ellipse(image,(l+a,t+b),(a,b),0,0,360,(255,0,255),2)
            test_img.append(image)
test_y = np.array(test_y)
#输出预测结果
pred_test_y = []
for face in test_x:
    pred_code = model.predict(face)[0]
    pred_test_y.append(pred_code)
escape = False
while not escape:
    for code,pred_code,image in zip(test_y,pred_test_y,test_img):
        label,pred_label = codec.inverse_transform([code,pred_code])
        text = '{} {} {}'.format(label,'=='if code == pred_code else '!=',pred_label)
        cv.putText(image,text,(20,100),cv.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)
        cv.imshow('recongnizing...',image)
        if cv.waitKey(1000)==27:
            escape = True
            break




你可能感兴趣的:(python opencv人脸识别)