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

Opencv Python face recognition sign in system

編輯:Python

List of articles

  • Preface
  • 1.1 Specific function description
  • 1.2 Precautions for use
  • 2.1 Specific code implementation
    • 2.1.1 Video capture face code
    • 2.1.2 Face recognition code
  • summary


Preface

Code implementation is not difficult , Personally, I think the biggest difficulty of this project is in loading , I've been tossing about for a long time .


notes : install dlib and face_recognition Ku took many detours , Please refer to my other blog for specific methods , No more details here .

1.1 Specific function description

First, call the camera to intercept and save the recognized face in the specified folder , Then run the identification code , The code generates a file named the date of the day excel form ( Path can be specified ), If the face in the specified folder is recognized , Will be in excel Write the name of the person and the check-in time in the form .

1.2 Precautions for use

Be careful :1、 Make sure that there is only one face in the picture when intercepting faces , And there must be no shelter ( Such as masks ), After saving to a specific folder, rename the photo to " The person's name . Suffix name ".
2、 If the identification file is run repeatedly on the same day , Last write excel The identification data will be overwritten .

2.1 Specific code implementation

2.1.1 Video capture face code

import cv2
cap = cv2.VideoCapture(0)
count = 1 # The number of the saved image , Used as file name 
while(cap.isOpened()):
ret,frame = cap.read()
cv2.imshow('frame',frame)
key = cv2.waitKey(1)
if key == ord('s'): # Press s Key screenshot save 
cv2.imwrite(r"D:face/"+str(count)+".jpg",frame) # Specify the save path 
count+=1
if key ==27: # Press Esc Key out of loop 
break
cap.release() # Release ( close ) camera 
cv2.destroyAllWindows() # Close the display window 

2.1.2 Face recognition code

notes : Remember to change the file name in the folder where the face is saved first .

import cv2
import numpy as np
import face_recognition
import os
import datetime
import xlwt
import xlrd
# Encoding handler 
def findEncodings(images):
encodeList = []
# First convert the picture to RGB Format 
# Then code it , Append to encodList in , Finally, return to this list 
for img in images:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
encode = face_recognition.face_encodings(img)[0] # Take the subscript [0] Facial information for ( Only one face can appear in the collected photos )
encodeList.append(encode)
return encodeList
def markAttendance(name):
global n
global namelist
#i Is the number of columns 
i = 0
# Determine whether the recognized person's name is in namelist in , If not, add , Prevent multiple sign ins 
if name not in namelist:
namelist.append(name)
# Open the built excel, Write the name of the person signing in and the time of signing in 
xlrd.open_workbook(r"C:/ Custom path "+str(datetime.date.today())+".xls",formatting_info=True)
worksheet.write(n,i,name)
i+=1
now = datetime.datetime.today()
nowtime = now.strftime('%H:%M:%S')
worksheet.write(n,i,nowtime)
i+=1
workbook.save(r"C:/ Custom path "+str(datetime.date.today())+".xls")
# Automatic line feed 
if (i % 2 ==0):
n+=1
if __name__ == "__main__":
# The path is the path of the photos saved in advance for comparison 
path = r'D:/face'
# Create two empty lists to store photos and names for comparison 
images = []
classNames = []
#myList The list is used to store the files in the path , Print the file name to check for errors 
myList = os.listdir(path)
print(myList)
# Read the picture into (curImg To read in pictures one by one , Add it to images In the list )
# The split file name is file name + Extension , Only keep the file name at className In the list 
for cl in myList:
curImg = cv2.imread(f'{
path}/{
cl}')
images.append(curImg)
classNames.append(os.path.splitext(cl)[0]) # Take the subscript [0], That is, the file name , Save to list 
print(classNames)
# take images Image encoding processing in the list 
encodeListKnown = findEncodings(images)
print('Encoding Complate')
# Create a camera 
cap = cv2.VideoCapture(0)
# Create a excel Form and initialize the form 、 Header , Then save 
workbook = xlwt.Workbook(encoding = 'utf-8')
worksheet = workbook.add_sheet(' Sign in today ')
worksheet.write(0,0,' full name ') # The first two parameters are the rows and columns of the table 
worksheet.write(0,1,' Check in time ')
workbook.save(r"C:/ Custom path "+str(datetime.date.today())+".xls")
#n Is the number of rows in the table ,namelist To identify the name of the person , Both are global variables 
n=1
namelist = []
# Into the loop , Camera starts to read in picture 
while True:
success,img = cap.read()
# Reduce the read in picture to a quarter of its original size , Improve processing efficiency 
imgSmall = cv2.resize(img, (0,0),None,0.25,0.25)
# Convert the reduced image to RGB passageway 
imgSmall = cv2.cvtColor(imgSmall, cv2.COLOR_BGR2RGB)
# Find the location of the face , Then it is encoded by lines 
faceCurFrame = face_recognition.face_locations(imgSmall)
encodeCurFrame = face_recognition.face_encodings(imgSmall,faceCurFrame)
# Traverse the coded image in the camera and the position of the face 
for encodeFace,faceLoc in zip(encodeCurFrame,faceCurFrame):
# Compare the face in the camera with the prepared face 
maches = face_recognition.compare_faces(encodeListKnown, encodeFace) # Comparing the results , Returns a Boolean value 
faceDis = face_recognition.face_distance(encodeListKnown, encodeFace) # Distance value , Equivalent to similarity , But the smaller the value, the more similar 
# Find the subscript with the smallest distance 
matchIndex = np.argmin(faceDis)
# Judge , If the element with the smallest distance is true 
if maches[matchIndex]:
# The person name corresponding to the recognized picture is changed to capital 
name = classNames[matchIndex].upper()
print(name)
# Find the coordinates of the four corners of the face 
y1,x2,y2,x1 = faceLoc
y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4 # Remember to get the face position by zooming out the image !! Because I want to draw on the original drawing , Here we have to go back 
# Draw a rectangle at the position of the recognized face 
# Draw a solid rectangle below this rectangle , Write the recognized name in this solid rectangle 
cv2.rectangle(img, (x1,y1), (x2,y2), (0,255,0),2)
cv2.rectangle(img, (x1,y2-35), (x2,y2), (0,255,0),cv2.FILLED)
cv2.putText(img, name, (x1+6,y2-6), cv2.FONT_HERSHEY_COMPLEX, 1, (255,255,255),2)
# Check in function 
markAttendance(name)
cv2.imshow('img', img)
key = cv2.waitKey(1)
if key==27: # Press Esc Key to exit 
break
cv2.destroyAllWindows()
cap.release()

summary

The general idea is not difficult , It can be done in half a day . I hope I can catch the little tail of winter vacation , Do a few more identification projects ~


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