程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python development guide [2] face model training and face recognition

編輯:Python

Python Development of guidelines [2] Face model training and face recognition

  • Beauty of procedure
  • Preface
  • The main body
    • Running effect
        • Face model training rendering
        • Face recognition rendering
        • Effect drawing of real-time face recognition by camera
    • Core code
        • Face model training core code
        • Face recognition core code
    • logic analysis
  • Conclusion

Beauty of procedure

Preface

Python As a programming language , The charm and influence of this language has gone far beyond C#、C++ And other programming language predecessors , Praised by programmers as “ good ” programing language .Python It is basically omnipotent , The system operational 、 Graph processing 、 Mathematical processing 、 Text processing 、 Database programming 、 Network programming 、web Programming 、 Multimedia applications 、pymo engine 、 Hacking 、 Reptile writing 、 machine learning 、 Artificial intelligence, etc ,Python Applications everywhere . Its advantages are self-evident , Easy to learn 、 High level language 、 Free and open source 、 Strong portability 、 Rich library 、 object-oriented 、 Extensibility 、 Embeddable 、 Standard code, etc ……
There are many beginners Python My little friends feel Python It's hard to learn , Read a book , Read and forget , Some online tutorials are vague , So it's hard to learn …
therefore , This column personally studies , practice , From easy to difficult , Layers of depth , Explain in detail what happened during commissioning , List the precautions one by one , I hope I can help you to learn Python Little buddy , Avoid detours , laborious .

The main body

In this article, let's learn Python Face model training and face recognition . Don't talk much , Let's take a look at the renderings first .

Running effect

Face model training rendering

Face recognition rendering

Effect drawing of real-time face recognition by camera


about Python Programming , Mainly basic grammar 、 Functions and modules 、 Regular expressions 、 Memory management and multithreading , That is to say Python The essence of .
1、 Basic grammar :Python Programming language variables 、 character 、 Common operators 、 Tuples and sets, etc ;
2、 object-oriented : This part is mainly to learn from understanding the characteristics of object-oriented and class , Then use the object-oriented application to handle the exceptions encountered ;
3、 Functions and modules , This part is mainly about the definition of learning function, standard module and third-party module 、 Implementation of customized package, etc ;
4、 Regular expressions , Regular expressions are important , Especially the little friends who want to engage in crawling , Be sure to learn regular expressions well ;
5、 Memory management and multithreading , It's about understanding Python Mechanism and mastery of programming language Python Multithreading .
beginner , Don't be afraid of trouble , Keep practicing , See what you are interested in , It's best to be able to do it yourself , Especially the redrawing of controls , Most exercise programming foundation .

Core code

Face model training core code

#!/usr/bin/env python
import threading
from logging import root
import cv2
import os
import sys
from PIL import Image
import numpy as np
def getImageAndLabels(path):
facesSamples=[]
ids=[]
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
print(imagePaths)
# Face detection
face_detector = cv2.CascadeClassifier(
'/home/fwy/AndroidStudio/OpenCV-android-sdk/sdk/etc/haarcascades/haarcascade_frontalface_default.xml')
# Traverse the images in the list
for imagePath in imagePaths:
# Open the picture
PIL_img = Image.open(imagePath).convert('L')
# Convert the image to an array
img_numpy = np.array(PIL_img,'uint8')
faces = face_detector.detectMultiScale(img_numpy)
# Get each picture of id
print(os.path.split(imagePath))
id = int(os.path.split(imagePath)[1].split('.')[0])
for x,y,w,h in faces:
facesSamples.append(img_numpy[y:y+h,x:x+w])
ids.append(id)
return facesSamples,ids
if __name__== '__main__':
# Picture path
path = './data/jm/'
# Get images Array and id label
faces,ids=getImageAndLabels(path)
# Get loop object
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces,np.array(ids))
# Save the file
recognizer.write('./data/trainer/trainer.yml')

Face recognition core code

#!/usr/bin/env python
import logging
import threading
import time
from logging import root
import cv2
import numpy as np
import os
# Get the current time
def get_current_time():
now = time.time()
mlsec = repr(now).split('.')[1][:3]
current_time = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec),time.localtime(now))
return current_time
# Log dynamic printing
def write_log_to_Text(logmsg):
current_time = get_current_time()
logmsg_in = str(current_time) +" " + str(logmsg) # Line break
logging.error(logmsg_in)
def recognizerFace(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face_detector = cv2.CascadeClassifier(
'/home/fwy/AndroidStudio/OpenCV-android-sdk/sdk/etc/haarcascades/haarcascade_frontalface_default.xml')
t = time.strftime("%H %M %S")
write_log_to_Text("start detection...")
faces = face_detector.detectMultiScale(gray, minNeighbors=30)
t = time.strftime("%H %M %S")
write_log_to_Text("end detection...")
#
# The confidence score is used to measure the distance between the recognition result and the original model .0 To indicate a perfect match .
# stay LBPH in : Usually , Think less than 50 The value of is acceptable , If the value is greater than 80 Think the difference is great .
# stay EigenFaces in : The value is usually in 0~20000 Between , As long as it's below 5000 Are considered to be quite reliable recognition results .
# stay Fisherfaces in : The value is usually in 0~20000 Between , As long as it's below 5000 Are considered to be quite reliable recognition results .
#
for x, y, w, h in faces:
id, confidence = recognizer.predict(gray[y:y + h, x:x + w]) # Face recognition
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
name = str(id)
cv2.putText(frame, name, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (80, 80, 80), 2)
print(' label id:', id, ' Confidence score :', confidence)
# Load training data and files
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('/home/fwy/PycharmProjects/FaceDetec/data/trainer/trainer.yml')
# Ready to recognize the picture
img = cv2.imread('/home/fwy/PycharmProjects/C360_2018-12-14-08-58-20-612.jpg')#1707.jpg
recognizerFace(img)
cv2.namedWindow('result', 0)
cv2.imshow('result',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

logic analysis

Face detection is OpenCV An important part of , It is also the basis of face recognition . Face recognition is actually a method that can recognize faces in a given image or video . In order to achieve this goal , We can use a series of classified images to “ Training ”, Propose a variety of facial features , Constitute a face feature database , Then, according to the face features of the given image, the features in the face database are compared , For identification , Face determination based on similarity . This is it. be based on OpenCV Face recognition model the whole process of face recognition . Another important feature of face recognition model is : Each identifier has a transpose message (confidence) The score is , That is what we call the score of a given similarity , It can be filtered and controlled by setting the threshold in practical application .

Get the data of face training database , These data need to be loaded into the face recognition algorithm for comparison . Of all face recognition models face_detector.detectMultiScale Function return value faces Array , every last face All have four parameters : Images x coordinate ,y coordinate ,w Face image width ,h Face image height . Through id, confidence = recognizer.predict(gray[y:y + h, x:x + w]) Function to get the face ID And confidence , Therefore, according to ID You can know who the identified person is . Do that , Need to 「trainer/」 Save in the directory as .yml file , That is, training face model file .

Conclusion

Okay , So much for today , I hope you can learn something from this article , I also sincerely hope to help those who are studying hard Python Programming partners , Your growth is my greatest happiness . Thank you very much for browsing my article in your busy schedule , Yes Source code You can trust me personally .
Source address :https://download.csdn.net/download/hnjzfwy/85774111


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved