Python realizes face sign-in system

The examples in this article share the specific code of python to realize the face sign-in system for your reference. The specific content is as follows

Simple face sign-in/sign-out system

The administrator can input face operations and export various check-in status tables;

Ordinary students can only perform check-in and check-out operations with [Face Recognition] (https://cloud.tencent.com/product/facerecognition?from=10680).

face_Recognizer.py

import cv2
import os
import numpy as np
from PIL import Image #pillow
import pyttsx3
import sys
import test.student_sql as connect #Import py
import test.recognizer_sql as baseConnect #Import py
import time
import json
def makeDir(engine):
flag=0if not os.path.exists("face_trainer"):print("Create a pre-training environment")
engine.say('The first boot is detected, the environment is not detected, the environment is being created')
engine.say('Creating pre-training environment')
os.mkdir("face_trainer")
engine.say('Created successfully')
engine.runAndWait()
flag=1if not os.path.exists("Facedata"):print("Create a training environment")
engine.say('Creating training environment')
os.mkdir("Facedata")
engine.say('Created successfully')
engine.runAndWait()
flag=1return flag
def getFace(cap,path_id):
# Call the notebook built-in camera, so the parameter is 0, if there are other cameras, you can adjust the parameters to 1, 2
# cap = cv2.VideoCapture(0)
# xml file is its own file path
face_detector = cv2.CascadeClassifier(r'F:\npyWorkspace\venv\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# face_id =input('\n enter user id:')print('\n Initializing face capture. Look at the camera and wait ...')
count =0while True:
# Read picture from camera
sucess, img = cap.read()
# Convert to grayscale image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Face detection
faces = face_detector.detectMultiScale(gray,1.3,5)for(x, y, w, h)in faces:
cv2.rectangle(img,(x, y),(x+w, y+w),(255,0,0))
count +=1
# Save image
cv2.imwrite("Facedata/User."+str(path_id)+'.'+str(count)+'.jpg', gray[y: y + h, x: x + w])
cv2.imshow('image', img)
# Keep the picture continuing.
k = cv2.waitKey(1)if k ==27: #Exit camera by esc key
break
elif count  =100: #Exit the camera after getting 1000 samples
break
cv2.destroyAllWindows()
def getImagesAndLabels(path, detector):
imagePaths =[os.path.join(path, f)for f in os.listdir(path)] #The role of join function
faceSamples =[]
ids =[]for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
img_numpy = np.array(PIL_img,'uint8')
id =int(os.path.split(imagePath)[-1].split(".")[1])
faces = detector.detectMultiScale(img_numpy)for(x, y, w, h)in faces:
faceSamples.append(img_numpy[y:y + h, x: x + w])
ids.append(id)return faceSamples, ids
def trainFace():
# Face data path
path ='Facedata'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier(r'F:\npyWorkspace\venv\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')print('Training faces. It will take a few seconds. Wait ...')
faces, ids =getImagesAndLabels(path, detector)
recognizer.train(faces, np.array(ids))
recognizer.write(r'face_trainer\trainer.yml')print("{0} faces trained. Exiting Program".format(len(np.unique(ids))))
def checkFace(cam,names,engine,sign_flag):
sex ={"female":"Ms","male":"Mr"}
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('face_trainer/trainer.yml')
cascadePath = r"F:\npyWorkspace\venv\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
font = cv2.FONT_HERSHEY_SIMPLEX
idnum =0
names =['yumengzhen','dujuanjuan','litingting','kangming','wangyizhe']
# 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 = faceCascade.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:
Name =connect.readName(idnum) #connect incoming ID student information table found return name
Sex =connect.readSex(idnum) #Connect ID student information table found and return Sex
StudentID =connect.readStudentID(idnum) #Connect ID student information table found to return studentID
# idnum = names[idnum] #Use the database to read the name corresponding to the id in the student information table
confidence ="{0}%".format(round(100- confidence))if sign_flag=='0': #Sign in
say(engine,"welcome"+Name+ sex[Sex]+"Sign in successfully")
baseConnect.insertd(idnum,Name,StudentID,Sex) #Insert check-in information into the check-in table
print("welcome"+Name+ sex[Sex]+"Sign in successfully")else:say(engine,"welcome "+Name+ sex[Sex]+"Sign out successfully")
baseConnect.insertt(idnum,Name,StudentID,Sex) #Insert check-out information in the check-in table
print("welcome"+Name+ sex[Sex]+"Sign out successfully")
cv2.imshow("img",img)
os.system("pause")returnelse:
idnum ="unknown"
confidence ="{0}%".format(round(100- confidence))
cv2.putText(img,str(idnum),(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(10)if k ==27:break
cam.release()
cv2.destroyAllWindows()
def say(engine,str):
engine.say(str)
engine.runAndWait()
def admission(): #Input information module
# names ={"yumengzhen":0,"dujuanjuan":1,"litingting":2}say(engine,"Please enter your student ID")
StudentID =input("Please enter student ID:")
# Read the database information table to retrieve the ID corresponding to Name
ID=connect.readIDbaseStudentID(StudentID) #connect input name student information table to find the return ID
if ID==-1:#The student was not found. Insert student information
while True:say(engine,"The student information was not found. Enter 0 Register 1 Re-enter")
op=input("\n If the student information is not found, enter the number 0 Registered student information 1 Re-enter")if op=='0':
Name,studentID,Sex=input("Enter student information: Name studentID Sex").split()
connect.insert(Name,studentID,Sex) #Insert student information
else:
StudentID =input("Please enter student ID:")
ID=connect.readIDbaseStudentID(StudentID) #connect input name student information table to find the return ID
if ID!=-1:breaksay(engine,"Opening camera")
cam = cv2.VideoCapture(0)say(engine,"Look at the camera and start collecting face data")getFace(cam, ID) #What is actually passed in is id
cam.release()if __name__ =='__main__':
names ={"yumengzhen":0,"dujuanjuan":1,"litingting":2}
password="123456" #password
engine = pyttsx3.init()
rate = engine.getProperty('rate')
engine.setProperty('rate', rate -20)
flag=makeDir(engine)
# trainFace()while True:if flag==1:
flag =0say(engine,"No face information for the first use")say(engine,"Whether to enter new face information")say(engine,"Enter 0 means to enter other means to exit")
value =input("0: Yes or other: No")if value=='0':while True:admission()say(engine,"Do you want to continue to enter new face information")say(engine,"Enter 0 means to enter other means to exit")
firstflag =input("0: Yes other: exit")if firstflag !='0':breaksay(engine,"After collecting, start training")trainFace()say(engine,"Finished training")
# say(engine,"Please choose login method")say(engine,"Enter 0 manager mode 1 to enter sign in/Sign-out mode 2 Exit student sign-in system")
user=input("\n0:Manager mode 1:Sign in/Sign out mode 2:Exit student sign-in system\n")if user=='0':say(engine,"Enter the administrator password")
pd=input("\nEnter the administrator password:\n")
count=1while True:if count==3:say(engine,"Enter the wrong password more than 3 times to force exit")breakif password == pd:say(engine,"Administrator mode")
# say(engine,"Enter the number 0 to export the sign-in table 1 to export the personal sign-in table 2 to export the time length table 3 to export the information table 4 to enter the face information 5 to exit")
op =input("\n0:Export all classmates sign-in table 1:Export personal sign-in form 2:Export all personnel time table 3:Export student information table 4 Enter face information 5 Exit\n")if op =='0':
baseConnect.sign()#Export check-in form
say(engine,"Export sign-in table successfully")
pass
elif op =='1':say(engine,"Enter the student ID of the exported student")
StudentID=input("Enter the student ID of the exported student")
ID=connect.readIDbaseStudentID(StudentID)if ID==-1:say(engine,"No student information")else:
baseConnect.peoson_sign(StudentID)#Export personal sign-in form
Name =connect.readName(ID) #connect incoming ID student information table found return name
say(engine,"Export"+Name+"Information success")
elif op =='2':
baseConnect.total_time()#Export time table
say(engine,"Export duration table successfully")
elif op =='3':
# Export student information table
connect.find_student_all()say(engine,"Export student information successfully")
elif op =='4':while True:admission()say(engine,"Do you want to continue to enter new face information")say(engine,"Enter 0 means to enter other means to exit")
secondflag =input("0: Yes other: exit")if secondflag !='0':breaksay(engine,"After collecting, start training")trainFace()say(engine,"Finished training")
elif op =='5':say(engine,"Exited administrator mode")breakelse:say(engine,"The input form is wrong, please re-enter")else:say(engine,"Please re-enter the wrong password")
pd =input("\nEnter the administrator password:\n")
count +=1;
elif user=='1':say(engine,"Welcome to sign in the student system/Sign out mode")
sign_flag=0;while True:say(engine,"Enter the number 0 to sign in 1 to sign out")
sign_flag =input("\n0:Sign in 1 Sign out\n")if sign_flag=='1' or sign_flag=='0':breakelse:say(engine,"Please enter the correct input form")say(engine,"Start face recognition")say(engine,"Opening camera")
cam = cv2.VideoCapture(0)checkFace(cam, names, engine,sign_flag)
elif user=='2':say(engine,"Information saved")say(engine,"Goodbye")
sys.exit(0)else:say(engine,"Input errors, please re-enter")

student_sql.py

student

import pymssql as py
import pandas as pd
# Connect to database, create student table, perform table query, table entry
server ="DESKTOP-XXX"#The server address to connect to your database
user ="sa"#Connect account
password ="123"#Connection password
conn = py.connect(server, user, password,"student_message") #Get connection
cursor = conn.cursor() #Get cursor
# Create table
cursor.execute("""
IF OBJECT_ID('students','U') IS NOT NULL
DROP TABLE students
CREATE TABLE students(
ID INT NOT NULL,
name VARCHAR(100),
StudentID INT,
Sex VARCHAR(100))""")
conn.commit()
# Create the table when you run it for the first time, and then you don’t need to build it again
def insert(Name, studentID, Sex):
count_students =0try:
conn = py.connect(server, user, password,"student_message") #Get connection
cursor =conn.cursor()
cursor.execute(' select count(ID) from students')for row in cursor:
count_students = row[0]print(row[0])
cursor.executemany("INSERT INTO students VALUES (%d, %s, %d,%s)",[(count_students+1, Name, studentID, Sex)])
# You must call commit()To keep your data submitted if you don’t set auto-submit to true
conn.commit()
conn.close()
except py.InterfaceError:print("Database connection error")
except py.ProgrammingError:print("Data error, please check the entered data")
except py.OperationalError:print("Data error, please check the entered data")
# Export student information table
def find_student_all():try:
conn = py.connect(server, user, password,"student_message") #Get connection
cursor =conn.cursor()
sql ="select * from students"
df = pd.read_sql(sql, conn)
df.to_excel('all.xlsx',index=False)print('ok')
conn.commit()
conn.close()
except py.InterfaceError:print("Database connection error")
except py.ProgrammingError:print("Data error, please check the entered data")
# find_student_all()
def readName(idnum):
Name =-1try:
conn = py.connect(server, user, password,"student_message") #Get connection
cursor =conn.cursor()
cursor.execute(' select Name from students where ID='+str(idnum))for row in cursor:if row[0]!=[]:
Name = row[0]
conn.commit()
conn.close()
except py.InterfaceError:print("Database connection error")
except py.ProgrammingError:print("Data error, please check the entered data")return Name
def readIDbaseStudentID(StudentID):
ID =-1try:
conn = py.connect(server, user, password,"student_message") #Get connection
cursor =conn.cursor()
cursor.execute(' select ID from students where StudentID='+str(StudentID))for row in cursor:if row[0]!=[]:
ID = row[0]
conn.commit()
conn.close()
except py.InterfaceError:print("Database connection error")
except py.ProgrammingError:print("Data error, please check the entered data")return ID
def readSex(idnum):
Sex =-1try:
conn = py.connect(server, user, password,"student_message") #Get connection
cursor =conn.cursor()
cursor.execute(' select Sex from students where ID='+str(idnum))for row in cursor:if row[0]!=[]:
Sex = row[0]
conn.commit()
conn.close()
except py.InterfaceError:print("Database connection error")
except py.ProgrammingError:print("Data error, please check the entered data")return Sex
def readID(name):
# Multiple id
ID =-1try:
conn = py.connect(server, user, password,"student_message") #Get connection
cursor =conn.cursor()
cursor.execute(' select ID from students where name='+'\''+str(name)+'\'')for row in cursor:if row[0]!=[]:
ID = row[0]
conn.commit()
conn.close()
except py.InterfaceError:print("Database connection error")
except py.ProgrammingError:print("Data error, please check the entered data")return ID
def readStudentID(idnum):
StudentID =-1try:
conn = py.connect(server, user, password,"student_message") #Get connection
cursor =conn.cursor()
cursor.execute(' select StudentID from students where ID='+str(idnum))for row in cursor:if row[0]!=[]:
StudentID = row[0]
conn.commit()
conn.close()
except py.InterfaceError:print("Database connection error")
except py.ProgrammingError:print("Data error, please check the entered data")return StudentID
# Close the connection
# conn.close()
#
# # Note: At any time, under a connection, only one cursor object will appear for a database operation being performed

recognizer_sql.py

import pymssql as py
import time
import pandas as pd
server ="DESKTOP-XXXX"#Connection server address
user ="sa" #Connect account
password ="123" #Connection password
conn = py.connect(server, user, password,"student_message") #Get connection
cursor = conn.cursor() #Get cursor
def insertd(idnum,Name,StudentID,Sex): #Sign in
conn = py.connect(server, user, password,"student_message") #Get connection
timenow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cursor = conn.cursor()
cursor.execute("INSERT INTO qiandao VALUES (%d, %s,%d,%s, %s, %s, %s,%d )",(idnum,Name,StudentID,Sex,timenow,'0','0',0))
conn.commit()
# Must call commit()To keep the data submitted
def insertt(idnum,Name,StudentID,Sex): #Sign out
conn = py.connect(server, user, password,"student_message") #Get connection
cursor = conn.cursor()
cursor.execute("SELECT starttime FROM qiandao WHERE ID=%s and flag=%d",(idnum,0))
starttimeget = cursor.fetchone()
sat =str(tuple(starttimeget))
timenow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
timeArray = time.strptime(sat,"('%Y-%m-%d %H:%M:%S',)")
timeStamp =int(time.mktime(timeArray))
timecout = time.time()- timeStamp
m, s =divmod(timecout,60)
h, m =divmod(m,60)
timepass =str(h)+'hour'+str(m)+'minute'+str(s)+'second'print(timepass)
cursor.executemany("INSERT INTO qiandao VALUES (%d, %s,%d,%s, %s, %s, %s,%d )",[(idnum,Name,StudentID,Sex,'0', timenow, timepass,1)])
conn.commit()
def peoson_sign(StudentID):#Export student information table_According to the student number
conn = py.connect(server, user, password,"student_message") #Get connection
cursor = conn.cursor()
sql ="select * from qiandao where StudentID="+str(StudentID)
df = pd.read_sql(sql, conn)
df.to_excel(r'E:\01STUDY\20190701\work\openVersion\excel\studentID_sign.xlsx',index=False)print('ok')
conn.commit()
# peoson_sign(2016002105)
def sign():#Export check-in form
conn = py.connect(server, user, password,"student_message") #Get connection
cursor = conn.cursor()
sql ="select * from qiandao"
df = pd.read_sql(sql, conn)
df.to_excel(r'E:\01STUDY\20190701\work\openVersion\excel\sign_all.xlsx', index=False)print('ok')
conn.commit()
# sign()
def total_time():#Export time table#sign()
conn = py.connect(server, user, password,"student_message") #Get connection
cursor = conn.cursor()
sql ="select * from qiandao where convert(nvarchar(max),count) != convert(nvarchar(max),0)"
df = pd.read_sql(sql, conn)
df.to_excel(r'E:\01STUDY\20190701\work\openVersion\excel\total_time.xlsx', index=False)print('ok')
conn.commit()
#
# if __name__=='__main':
# sign()
# # peoson_sign(2016002105)
conn.close()

For more learning materials, please pay attention to the topic "Management System Development".

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Python realizes face sign-in system
Python realizes business card management system
Python3 realizes business card management system
Python realizes express price query system
Python realizes the development of student management system
Python realizes spaceship war
Python realizes stitching pictures
Python realizes online translation
Python realizes tank battle
Python realizes online translation function
Python implements parking management system
Python realizes apple eating game
Python realizes the guessing game
Python realizes 3D map visualization
Python implements car management system
Python realizes batch naming photos
Python implements student performance evaluation system
Implementing student management system with python
Python business card management system development
Python implements AI face change function
Python version business card management system
Python realizes online microblog data visualization
Implementation of python student management system
Python implements the actual banking system
Python realizes image recognition car function
Python realizes udp transmission picture function
Python realizes console output color font