10 minutes taught you how to use simple Python implementation of face recognition

To directly download the code file, pay attention to our public No. Oh! View history messages can be!

Preface: I know my computer

My computer just to know me, just call with my computer!

↑ handsome small series!

Today, we use the Python implementation on a tall face recognition technology !

Python, the simple recognition There are many ways to achieve, depending on the python glue language features, we can quickly and accurately to achieve this goal by calling package. Here is the introduction of a relatively high accuracy.

01 First

Face recognition needs to sort out what steps to achieve:

Processes generally the case, before this, people must first face was accurate to find out, which is able to accurately distinguish the face classifier, where we can have the trained classifier, Internet species than the whole, the classification accuracy is relatively high, we can also save time spent in this area.

ps: Baby sources of small series have been placed below link in friends ~

Recommended: GITHUB

https://github.com/opencv/opencv/tree/master/data/haarcascades

Since using a python, it uses natural and ultimately package, before looking at the code, we first needed to package the entire project list at:

· CV2 (Opencv): image recognition, camera call

· Os: File Operations

Numpy ·: NumPy (Numerical Python) is an extension library Python language, supports a number of dimensions of the array and matrix operations, in addition, it provides a lot of math library for Array Operations

PIL ·: Python Imaging Library, Python standard library of image processing platform in fact the

02 Next

2.1 Face to obtain control

#-----获取人脸样本-----
import cv2

#调用笔记本内置摄像头,参数为0,如果有其他的摄像头可以调整参数为1,2
cap = cv2.VideoCapture(0)
#调用人脸分类器,要根据实际路径调整3
face_detector = cv2.CascadeClassifier(r'X:/Users/73950/Desktop/FaceRec/haarcascade_frontalface_default.xml')  #待更改
#为即将录入的脸标记一个id
face_id = input('\n User data input,Look at the camera and wait ...')
#sampleNum用来计数样本数目
count = 0

while True:    
    #从摄像头读取图片
    success,img = cap.read()    
    #转为灰度图片,减少程序符合,提高识别度
    if success is True: 
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    else:   
        break
    #检测人脸,将每一帧摄像头记录的数据带入OpenCv中,让Classifier判断人脸
    #其中gray为要检测的灰度图像,1.3为每次图像尺寸减小的比例,5为minNeighbors
    faces = face_detector.detectMultiScale(gray, 1.3, 5)

    #框选人脸,for循环保证一个能检测的实时动态视频流
    for (x, y, w, h) in faces:
        #xy为左上角的坐标,w为宽,h为高,用rectangle为人脸标记画框
        cv2.rectangle(img, (x, y), (x+w, y+w), (255, 0, 0))
        #成功框选则样本数增加
        count += 1  
        #保存图像,把灰度图片看成二维数组来检测人脸区域
        #(这里是建立了data的文件夹,当然也可以设置为其他路径或者调用数据库)
        cv2.imwrite("data/User."+str(face_id)+'.'+str(count)+'.jpg',gray[y:y+h,x:x+w]) 
        #显示图片
        cv2.imshow('image',img)       
        #保持画面的连续。waitkey方法可以绑定按键保证画面的收放,通过q键退出摄像
    k = cv2.waitKey(1)        
    if k == '27':
        break        
        #或者得到800个样本后退出摄像,这里可以根据实际情况修改数据量,实际测试后800张的效果是比较理想的
    elif count >= 800:
        break

#关闭摄像头,释放资源
cap.realease()
cv2.destroyAllWindows()

Xiaobian test, in execution

“face_detector = cv2.CascadeClssifier(r'C:\Users\admin\Desktop\python\data\haarcascade_frontalface_default.xml')”此语句时,实际路径中的目录名尽量不要有中文字符出现,否则容易报错。

这样,你的电脑就能看到你啦!

2.2 通过算法建立对照模型

本次所用的算法为opencv中所自带的算法,opencv较新版本中(我使用的是2.4.8)提供了一个FaceRecognizer类,里面有相关的一些人脸识别的算法及函数接口,其中包括三种人脸识别算法(我们采用的是第三种)

1.eigenface

2.fisherface

3.LBPHFaceRecognizer

LBP是一种特征提取方式,能提取出图像的局部的纹理特征,最开始的LBP算子是在3X3窗口中,取中心像素的像素值为阀值,与其周围八个像素点的像素值比较,若像素点的像素值大于阀值,则此像素点被标记为1,否则标记为0。这样就能得到一个八位二进制的码,转换为十进制即LBP码,于是得到了这个窗口的LBP值,用这个值来反映这个窗口内的纹理信息。

LBPH是在原始LBP上的一个改进,在opencv支持下我们可以直接调用函数直接创建一个LBPH人脸识别的模型。

我们在前一部分的同目录下创建一个Python文件,文件名为trainner.py,用于编写数据集生成脚本。同目录下,创建一个文件夹,名为trainner,用于存放我们训练后的识别器。

#-----建立模型、创建数据集-----#-----建立模型、创建数据集-----

import os
import cv2
import numpy as np
from PIL import Image
#导入pillow库,用于处理图像
#设置之前收集好的数据文件路径
path = 'data'

#初始化识别的方法
recog = cv2.face.LBPHFaceRecognizer_create()

#调用熟悉的人脸分类器
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

#创建一个函数,用于从数据集文件夹中获取训练图片,并获取id
#注意图片的命名格式为User.id.sampleNum
def get_images_and_labels(path):
    image_paths = [os.path.join(path,f) for f in os.listdir(path)]
    #新建连个list用于存放
    face_samples = []
    ids = []

    #遍历图片路径,导入图片和id添加到list中
    for image_path in image_paths:

        #通过图片路径将其转换为灰度图片
        img = Image.open(image_path).convert('L')

        #将图片转化为数组
        img_np = np.array(img,'uint8')

        if os.path.split(image_path)[-1].split(".")[-1] != 'jpg':
            continue

        #为了获取id,将图片和路径分裂并获取
        id = int(os.path.split(image_path)[-1].split(".")[1])
        faces = detector.detectMultiScale(img_np)

        #将获取的图片和id添加到list中
        for(x,y,w,h) in faces:
            face_samples.append(img_np[y:y+h,x:x+w])
            ids.append(id)
    return face_samples,ids

#调用函数并将数据喂给识别器训练
print('Training...')
faces,ids = get_images_and_labels(path)
#训练模型
recog.train(faces,np.array(ids))
#保存模型
recog.save('trainner/trainner.yml')

这就让电脑认识到你是与众不同的那颗星~

image

2.3 识别

检测,校验,输出其实都是识别的这一过程,与前两个过程不同,这是涉及实际使用的过程,所以我们把他整合放在一个统一的一个文件内。

#-----检测、校验并输出结果-----
import cv2

#准备好识别方法
recognizer = cv2.face.LBPHFaceRecognizer_create()

#使用之前训练好的模型
recognizer.read('trainner/trainner.yml')

#再次调用人脸分类器
cascade_path = "haarcascade_frontalface_default.xml" 
face_cascade = cv2.CascadeClassifier(cascade_path)

#加载一个字体,用于识别后,在图片上标注出对象的名字
font = cv2.FONT_HERSHEY_SIMPLEX

idnum = 0
#设置好与ID号码对应的用户名,如下,如0对应的就是初始

names = ['初始','admin','user1','user2','user3']

#调用摄像头
cam = cv2.VideoCapture(0)
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)

while True:
    ret,img = cam.read()
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    #识别人脸
    faces = face_cascade.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)
        idnum,confidence = recognizer.predict(gray[y:y+h,x:x+w])

        #计算出一个检验结果
        if confidence < 100:
            idum = names[idnum]
            confidence = "{0}%",format(round(100-confidence))
        else:
            idum = "unknown"
            confidence = "{0}%",format(round(100-confidence))

        #输出检验结果以及用户名
        cv2.putText(img,str(idum),(x+5,y-5),font,1,(0,0,255),1)
        cv2.putText(img,str(confidence),(x+5,y+h-5),font,1,(0,0,0),1)

        #展示结果
        cv2.imshow('camera',img)
        k = cv2.waitKey(20)
        if k == 27:
            break

#释放资源
cam.release()
cv2.destroyAllWindows()

现在,你的电脑就能识别出你来啦!

Other combinations can also be achieved through a variety of functions such as start testing, you learn it?

The following is a small series of test results and review some of the problems oh we want to help (bared teeth .jpg)

Test Results

Photos stored in the data directory after Pictured is converted to grayscale images

Successful small series of stars identified face (bared teeth .jpg)

Xiao Bian review emerging issues during testing:

(1) version issues

Solution: After numerous failures of small series, we had better be prompted to install python2.7, can be used directly pip install numpy and pip install opencv-python numpy and install the corresponding version of python opencv

(If you are using Anaconda2, Anaconda Prompt pip related commands folder under the Start menu Anaconda2 file input)

Click on the link Tweets given after the github file download release to the next folder where files are compiled, and change the code in the relevant directory

(2) If the prompt "module 'object has no attribute' face '"

Solution: enter pip install opencv-contrib-python solution, if prompted Commission, --user can be added later, i.e. pip install opencv-contrib-python --user

If you have other questions please feel free to contact us we ah

Guess you like

Origin www.cnblogs.com/dengfaheng/p/10959134.html