├── StudentDetails
└── StudentDetails.csv
├── Face_Recogniser 13-06-2020 9.14.42 PM.png
├── required.txt
├── README.md
└── train.py
/StudentDetails/StudentDetails.csv:
--------------------------------------------------------------------------------
1 | Id,Name
2 |
--------------------------------------------------------------------------------
/Face_Recogniser 13-06-2020 9.14.42 PM.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/imbansalaniket/Facial-Recognition-Attandance-System-Using-Python/HEAD/Face_Recogniser 13-06-2020 9.14.42 PM.png
--------------------------------------------------------------------------------
/required.txt:
--------------------------------------------------------------------------------
1 | cx-Freeze==6.0
2 | DateTime==4.3
3 | idna==2.8
4 | numpy==1.17.3
5 | opencv-contrib-python==4.2.0.34
6 | opencv-python==4.1.1.26
7 | pandas==1.0.4
8 | Pillow==7.1.2
9 | python-dateutil==2.8.0
10 | pytz==2019.3
11 | six==1.12.0
12 | zope.interface==4.6.0
13 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | To run this project on your machine, after unzipping the project follow these commands:
2 |
3 | -
4 | Create Several Empty directories with these exact names:
5 |
6 | - Attendance
7 | - ImagesUnknown
8 | - TrainingImage
9 | - TrainingImageLabel
10 |
11 |
12 | - Then open Command Prompt in same Project directory and run these Commands:
13 |
14 | (Assuming you have Python3 and pip installed)
15 |
16 | - pip install -r required.txt --user
17 | - pip install -r opencv-contrib-python --upgrade --user
18 | Now you are all set to start this project, just start by this command:
19 | - python train.py
20 |
21 |
22 | - You will be shown a window like this:
23 |
24 |
25 | - Enter Numeric value for Id.
26 | - Enter your Name in the field provided.
27 | - Click on Take Images.
28 |
29 | (Another window will open and your webcam will be activated you can see it is taking your picture to train its model.
30 |
31 | The window will close automatically,if it doesn't press q to close it.)
32 |
33 | - Click on Train Images.
34 | - Now Click on Track Images.
35 |
36 | (Another window will open and your webcam will be activated you can see it is showing your name below your face.)
37 |
38 | - Press q to close the window.
39 | - Now go to your project diectory and open Attendance folder(remember you created blank folders).
40 |
41 | Here you can see a .csv file is created open it with excel you can see it contains your name id and a datestamp of you when you tracked the image.
42 |
43 |
44 | Similarly You can train it for multiple peoples.(Place one person in the frame while taking the image.)
45 |
46 | Although try with multiple people in the frame when you are marking the attandance i.e. Tracking Images.
47 |
48 |
49 | For further assistance raise a Issue.
50 |
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | import tkinter as tk
2 | from tkinter import Message ,Text
3 | import cv2,os
4 | import shutil
5 | import csv
6 | import numpy as np
7 | from PIL import Image, ImageTk
8 | import pandas as pd
9 | import datetime
10 | import time
11 | import tkinter.ttk as ttk
12 | import tkinter.font as font
13 |
14 | window = tk.Tk()
15 | #helv36 = tk.Font(family='Helvetica', size=36, weight='bold')
16 | window.title("Face_Recogniser")
17 |
18 | dialog_title = 'QUIT'
19 | dialog_text = 'Are you sure?'
20 | #answer = messagebox.askquestion(dialog_title, dialog_text)
21 |
22 | window.geometry('1280x720')
23 | window.configure(background='grey')
24 |
25 | #window.attributes('-fullscreen', True)
26 |
27 | window.grid_rowconfigure(0, weight=1)
28 | window.grid_columnconfigure(0, weight=1)
29 |
30 | #path = "profile.jpg"
31 |
32 | #Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
33 | #img = ImageTk.PhotoImage(Image.open(path))
34 |
35 | #The Label widget is a standard Tkinter widget used to display a text or image on the screen.
36 | #panel = tk.Label(window, image = img)
37 |
38 |
39 | #panel.pack(side = "left", fill = "y", expand = "no")
40 |
41 | #cv_img = cv2.imread("img541.jpg")
42 | #x, y, no_channels = cv_img.shape
43 | #canvas = tk.Canvas(window, width = x, height =y)
44 | #canvas.pack(side="left")
45 | #photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img))
46 | # Add a PhotoImage to the Canvas
47 | #canvas.create_image(0, 0, image=photo, anchor=tk.NW)
48 |
49 | #msg = Message(window, text='Hello, world!')
50 |
51 | # Font is a tuple of (font_family, size_in_points, style_modifier_string)
52 |
53 |
54 |
55 | message = tk.Label(window, text="Face-Recognition-Based-Attendance-Management-System" ,fg="black", bg="grey" ,font=('times', 30, 'italic bold underline'))
56 |
57 | message.place(x=200, y=20)
58 |
59 | lbl = tk.Label(window, text="Enter ID",width=20 ,height=2, bg="grey" ,font=('times', 15, ' bold ') )
60 | lbl.place(x=400, y=200)
61 |
62 | txt = tk.Entry(window,width=20 ,bg="white" ,font=('times', 15, ' bold '))
63 | txt.place(x=700, y=215)
64 |
65 | lbl2 = tk.Label(window, text="Enter Name",width=20 ,bg="grey" ,height=2 ,font=('times', 15, ' bold '))
66 | lbl2.place(x=400, y=300)
67 |
68 | txt2 = tk.Entry(window,width=20 ,bg="white" ,font=('times', 15, ' bold ') )
69 | txt2.place(x=700, y=315)
70 |
71 | lbl3 = tk.Label(window, text="Notification : ",width=20 ,bg="grey" ,height=2 ,font=('times', 15, ' bold '))
72 | lbl3.place(x=400, y=400)
73 |
74 | message = tk.Label(window, text="" ,bg="grey" ,width=30 ,height=2, activebackground = "yellow" ,font=('times', 15, ' bold '))
75 | message.place(x=700, y=400)
76 |
77 | lbl3 = tk.Label(window, text="Attendance : ",width=20 ,bg="grey" ,height=2 ,font=('times', 15, ' bold underline'))
78 | lbl3.place(x=400, y=600)
79 |
80 |
81 | message2 = tk.Label(window, text="" ,bg="grey",activeforeground = "green",width=30 ,height=2 ,font=('times', 15, ' bold '))
82 | message2.place(x=700, y=600)
83 |
84 | def clear():
85 | txt.delete(0, 'end')
86 | res = ""
87 | message.configure(text= res)
88 |
89 | def clear2():
90 | txt2.delete(0, 'end')
91 | res = ""
92 | message.configure(text= res)
93 |
94 | def is_number(s):
95 | try:
96 | float(s)
97 | return True
98 | except ValueError:
99 | pass
100 |
101 | try:
102 | import unicodedata
103 | unicodedata.numeric(s)
104 | return True
105 | except (TypeError, ValueError):
106 | pass
107 |
108 | return False
109 |
110 | def TakeImages():
111 | Id=(txt.get())
112 | name=(txt2.get())
113 | if(is_number(Id) and name != ""):
114 | cam = cv2.VideoCapture(0)
115 | harcascadePath = "haarcascade_frontalface_default.xml"
116 | detector=cv2.CascadeClassifier(harcascadePath)
117 | sampleNum=0
118 | while(True):
119 | ret, img = cam.read()
120 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
121 | faces = detector.detectMultiScale(gray, 1.3, 5)
122 | for (x,y,w,h) in faces:
123 | cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
124 | #incrementing sample number
125 | sampleNum=sampleNum+1
126 | #saving the captured face in the dataset folder TrainingImage
127 | cv2.imwrite("TrainingImage\ "+name +"."+Id +'.'+ str(sampleNum) + ".jpg", gray[y:y+h,x:x+w])
128 | #display the frame
129 | cv2.imshow('frame',img)
130 | #wait for 100 miliseconds
131 | if cv2.waitKey(100) & 0xFF == ord('q'):
132 | break
133 | # break if the sample number is morethan 100
134 | elif sampleNum>60:
135 | break
136 | cam.release()
137 | cv2.destroyAllWindows()
138 | res = "Images Saved for ID : " + Id +" Name : "+ name
139 | row = [Id , name]
140 | with open('StudentDetails\StudentDetails.csv','a+') as csvFile:
141 | writer = csv.writer(csvFile)
142 | writer.writerow(row)
143 | csvFile.close()
144 | message.configure(text= res)
145 | else:
146 | if(is_number(Id)):
147 | res = "Enter Alphabetical Name"
148 | message.configure(text= res)
149 | if(name.isalpha()):
150 | res = "Enter Numeric Id"
151 | message.configure(text= res)
152 |
153 | def TrainImages():
154 | recognizer = cv2.face_LBPHFaceRecognizer.create()#recognizer = cv2.face.LBPHFaceRecognizer_create()#$cv2.createLBPHFaceRecognizer()
155 | harcascadePath = "haarcascade_frontalface_default.xml"
156 | detector =cv2.CascadeClassifier(harcascadePath)
157 | faces,Id = getImagesAndLabels("TrainingImage")
158 | recognizer.train(faces, np.array(Id))
159 | recognizer.save("TrainingImageLabel\Trainner.yml")
160 | res = "Image Trained"#+",".join(str(f) for f in Id)
161 | message.configure(text= res)
162 |
163 | def getImagesAndLabels(path):
164 | #get the path of all the files in the folder
165 | imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
166 | #print(imagePaths)
167 |
168 | #create empth face list
169 | faces=[]
170 | #create empty ID list
171 | Ids=[]
172 | #now looping through all the image paths and loading the Ids and the images
173 | for imagePath in imagePaths:
174 | #loading the image and converting it to gray scale
175 | pilImage=Image.open(imagePath).convert('L')
176 | #Now we are converting the PIL image into numpy array
177 | imageNp=np.array(pilImage,'uint8')
178 | #getting the Id from the image
179 | Id=int(os.path.split(imagePath)[-1].split(".")[1])
180 | # extract the face from the training image sample
181 | faces.append(imageNp)
182 | Ids.append(Id)
183 | return faces,Ids
184 |
185 | def TrackImages():
186 | recognizer = cv2.face.LBPHFaceRecognizer_create()#cv2.createLBPHFaceRecognizer()
187 | recognizer.read("TrainingImageLabel\Trainner.yml")
188 | harcascadePath = "haarcascade_frontalface_default.xml"
189 | faceCascade = cv2.CascadeClassifier(harcascadePath);
190 | df=pd.read_csv("StudentDetails\StudentDetails.csv")
191 | cam = cv2.VideoCapture(0)
192 | font = cv2.FONT_HERSHEY_SIMPLEX
193 | col_names = ['Id','Name','Date','Time']
194 | attendance = pd.DataFrame(columns = col_names)
195 | while True:
196 | ret, im =cam.read()
197 | gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
198 | faces=faceCascade.detectMultiScale(gray, 1.2,5)
199 | for(x,y,w,h) in faces:
200 | cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
201 | Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
202 | if(conf < 60):
203 | ts = time.time()
204 | date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
205 | timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
206 | aa=df.loc[df['Id'] == Id]['Name'].values
207 | tt=str(Id)+"-"+aa
208 | attendance.loc[len(attendance)] = [Id,aa,date,timeStamp]
209 |
210 | else:
211 | Id='Unknown'
212 | tt=str(Id)
213 | # if(conf > 50):
214 | # noOfFile=len(os.listdir("ImagesUnknown"))+1
215 | # cv2.imwrite("ImagesUnknown\Image"+str(noOfFile) + ".jpg", im[y:y+h,x:x+w])
216 | cv2.putText(im,str(tt),(x,y+h), font, 1,(255,255,255),2)
217 | attendance=attendance.drop_duplicates(subset=['Id'],keep='first')
218 | cv2.imshow('im',im)
219 | if (cv2.waitKey(1)==ord('q')):
220 | break
221 | ts = time.time()
222 | date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
223 | timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
224 | Hour,Minute,Second=timeStamp.split(":")
225 | fileName="Attendance\Attendance_"+date+"_"+Hour+"-"+Minute+"-"+Second+".csv"
226 | attendance.to_csv(fileName,index=False)
227 | cam.release()
228 | cv2.destroyAllWindows()
229 | # print(attendance)
230 | res=attendance
231 | message2.configure(text= res)
232 |
233 |
234 | clearButton = tk.Button(window, text="Clear", command=clear ,width=5 ,height=1 ,activebackground = "Red" ,font=('times', 15, ' bold '))
235 | clearButton.place(x=950, y=210)
236 | clearButton2 = tk.Button(window, text="Clear", command=clear2 ,width=5 ,height=1, activebackground = "Red" ,font=('times', 15, ' bold '))
237 | clearButton2.place(x=950, y=310)
238 | takeImg = tk.Button(window, text="Take Images", command=TakeImages ,width=10 ,height=1, activebackground = "Red" ,font=('times', 15, ' bold '))
239 | takeImg.place(x=200, y=500)
240 | trainImg = tk.Button(window, text="Train Images", command=TrainImages ,width=10 ,height=1, activebackground = "Red" ,font=('times', 15, ' bold '))
241 | trainImg.place(x=500, y=500)
242 | trackImg = tk.Button(window, text="Track Images", command=TrackImages ,width=10 ,height=1, activebackground = "Red" ,font=('times', 15, ' bold '))
243 | trackImg.place(x=800, y=500)
244 | quitWindow = tk.Button(window, text="Quit", command=window.destroy ,width=10 ,height=1, activebackground = "Red" ,font=('times', 15, ' bold '))
245 | quitWindow.place(x=1100, y=500)
246 |
247 |
248 | window.mainloop()
--------------------------------------------------------------------------------