Home  >  Article  >  Backend Development  >  Learn to implement simple face recognition using Python

Learn to implement simple face recognition using Python

coldplay.xixi
coldplay.xixiforward
2021-03-22 10:16:073542browse

Learn to implement simple face recognition using Python

Preface

Let my computer know me. Only when my computer knows me can it be called my computer!

Today, we use Python to implement simple face recognition technology!

In Python, there are many ways to achieve simple face recognition. Depending on the characteristics of the python glue language, we can quickly and accurately achieve this goal by calling the package. The one introduced here is one with higher accuracy.

(Free learning recommendation: python video tutorial)

1. First

sort out the steps required to achieve face recognition:

The process is roughly like this. Before that, the face must first be Find it accurately, that is, a classifier that can accurately distinguish faces. Here we can use already trained classifiers. There are more types online and the classification accuracy is relatively high. We can also save time spent in this aspect. .

ps: The blogger’s treasure source has been placed in the link below~

Recommendation: GitHub project

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

Since we are using python, the use of packages is naturally indispensable. Before looking at the code, let us first list the packages required for the entire project:

· CV2 (Opencv): Image recognition, camera call

· os: File operation

· numpy: NumPy( Numerical Python) is an extension library of the Python language that supports a large number of dimensional array and matrix operations. In addition, it also provides a large number of mathematical function libraries for array operations

· PIL: Python Imaging Library , the de facto standard library for image processing on the Python platform

2. Next

1. Obtain

#-----获取人脸样本-----
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()
## by comparing the face #After testing by the blogger, when executing the statement

"face_detector = cv2.CascadeClssifier(r'C:\Users\admin\Desktop\python\data\haarcascade_frontalface_default.xml')", the actual path Try not to have Chinese characters in the directory name, otherwise an error will be easily reported.

This way, your computer can see you!

2. Establish a comparison model through algorithms

The algorithm used this time is the algorithm included in

opencv, opencv is relatively The new version (I am using 2.4.8) provides a FaceRecognizer class, which contains some related face recognition algorithms and function interfaces, including threefaceidentificationAlgorithm (we use the third one)

1.eigenface

2.fisherface

3.LBPHFaceRecognizer

LBP is a feature extraction method that can extract local texture features of an image. The initial LBP operator takes the pixel value of the center pixel as the threshold in a 3X3 window and compares it with the pixel values ​​of the eight surrounding pixels. , if the pixel value of the pixel is greater than the threshold, the pixel is marked as 1, otherwise it is marked as 0. In this way, an eight-bit binary code can be obtained, which is converted into decimal or LBP code, so the LBP value of this window is obtained, and this value is used to reflect the texture information in this window.

LBPH is an improvement on the original LBP. With opencv support, we can directly call the function to directly create an LBPH

face recognition model.

We create a Python file in the same directory as the previous part, the file name is trainner.py, which is used to write the data set generation script. In the same directory, create a folder named trainner to store our trained recognizer.

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

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')

This will let the computer realize that you are the unique star~

3. Recognition

Detection, verification, and output are actually the process of

identifying. Different from the first two processes, this is a process involving actual use, so we integrate it into a unified file.

#-----检测、校验并输出结果-----
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 <p>Now, your computer can recognize you! <strong></strong></p>Various functions such as power-on detection can also be realized through other combinations. Have you learned it? <p></p>The following are the test results and some problems that occurred when the blogger reviewed the manuscript ~ I hope it will be helpful to everyone (呲ya.jpg) <p></p><p>Test results: <strong></strong></p><p><img alt="Learn to implement simple face recognition using Python" src="https://img.php.cn/upload/article/000/000/052/53329dfc75f057b5271d004ca1012368-1.png"></p><p><img alt="Learn to implement simple face recognition using Python" src="https://img.php.cn/upload/article/000/000/052/53329dfc75f057b5271d004ca1012368-2.png"></p><p> Problems that occurred during the blogger review and test process: <strong></strong></p><p>( 1) Version problem<strong></strong></p><p>Solution:<strong>After numerous failures from bloggers, we are reminded that it is best to install python2.7. You can directly use pip install numpy and pip install opencv- python installs numpy and the corresponding python version of opencv</strong></p><p> (If you are using Anaconda2, pip related commands can be entered in Anaconda Prompt under the Anaconda2 folder in the start menu) </p><p>Click the link given in the tweet, download the file in github and put it in In the folder where the compiled file is located, and change the relevant directories in the code</p><p><strong>(2) If it prompts "module' object has no attribute 'face'"</strong></p><p><strong>Solution: </strong>You can enter pip install opencv-contrib-python to solve the problem. If you are prompted that commission is required, you can add --user after it, that is, pip install opencv-contrib-python --user</p><p> If you have any other questions, please feel free to contact the blogger at any time~~~</p><blockquote><p><strong>There are a lot of free learning recommendations, please visit </strong><a href="https://www.php.cn/course/list/30.html" target="_blank"><strong>python tutorial</strong></a><strong>(video)</strong></p></blockquote>

The above is the detailed content of Learn to implement simple face recognition using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete