The whole code for the program is given below. Detailed description will be given in the upcoming blogs.
import tkinter as tk
from cv2 import cv2
import time
import datetime as dt
from PIL import Image,ImageTk
import argparse
import numpy
import os
import pandas as pd
class App:
def __init__(self,window,video_source=0):
self.window=window
self.window.title("Smart Attendance System")
self.window.config(bg="black")
self.video_source=video_source
self.ok=False
self.vid=VideoCapture(self.video_source)
self.canvas=tk.Canvas(window,width=self.vid.width,height=self.vid.height)
self.canvas.grid(row=0,column=0,padx=20,pady=(20,0))
self.timer=ElapsedTimeClock(self.window)
self.button_frame=tk.Frame(self.window,bg="gray",width=self.vid.width)
self.button_frame.grid(row=2,column=0,padx=10,pady=10)
self.btn_snapshot=tk.Button(self.button_frame,text="Add Student",command=self.add_student)
self.btn_snapshot.grid(row=0,column=0,ipadx=10)
self.btn_snapshot=tk.Button(self.button_frame,text="Train Model",command=self.train_model)
self.btn_snapshot.grid(row=0,column=1,ipadx=10)
self.btn_snapshot=tk.Button(self.button_frame,text="Start Class",command=self.start_class)
self.btn_snapshot.grid(row=0,column=2,ipadx=10)
self.btn_snapshot=tk.Button(self.button_frame,text="Get Attendance",command=self.get_attendance)
self.btn_snapshot.grid(row=0,column=3,ipadx=10)
self.btn_snapshot=tk.Button(self.button_frame,text="Snapshot",command=self.snapshot)
self.btn_snapshot.grid(row=0,column=4,ipadx=10)
self.btn_snapshot=tk.Button(self.button_frame,text="Start Recording",command=self.start_recording)
self.btn_snapshot.grid(row=0,column=5,ipadx=10)
self.btn_snapshot=tk.Button(self.button_frame,text="Stop Recording",command=self.stop_recording)
self.btn_snapshot.grid(row=0,column=6,ipadx=10)
self.btn_snapshot=tk.Button(self.button_frame,text="Quit",command=quit)
self.btn_snapshot.grid(row=0,column=7,ipadx=10)
self.window.iconbitmap("resources/icons/ai.ico")
self.get_time()
self.window.mainloop()
def snapshot(self):
ret,frame=self.vid.get_frame()
if ret:
path="snapshots/{}".format(str(dt.datetime.now().date()))
if (not os.path.isdir(path)):
os.mkdir(path)
path="snapshots/{}/{}".format(str(dt.datetime.now().date()),subject_now)
if (not os.path.isdir(path)):
os.mkdir(path)
cv2.imwrite(path+"/image"+time.strftime("%d-%m-%Y-%H-%M-%S")+".jpg",cv2.cvtColor(frame,cv2.COLOR_RGB2BGR))
def start_recording(self):
self.ok=True
self.timer.start()
def stop_recording(self):
self.ok=False
self.timer.stop()
def update(self):
self.delay=10
ret,frame=self.vid.get_frame()
if self.ok:
self.vid.out.write(cv2.cvtColor(frame,cv2.COLOR_RGB2BGR))
if ret:
self.photo=ImageTk.PhotoImage(image=Image.fromarray(frame))
self.canvas.create_image(0,0,image=self.photo,anchor=tk.NW)
self.window.after(self.delay,self.update)
def get_attendance(self):
present_students=[]
path="attendance/{}".format(str(dt.datetime.now().date()))
if (not os.path.isdir(path)):
os.mkdir(path)
path="attendance/{}/{}".format(str(dt.datetime.now().date()),subject_now)
if (not os.path.isdir(path)):
os.mkdir(path)
attendance_sheet=open(path+"/attendance_"+time.strftime("%d-%m-%Y-%H-%M-%S")+".txt","a")
attendance_sheet.write("\nAttendance for "+ subject_now + "\n")
attendance_sheet.write("Timestamp: " + str(dt.datetime.now()) + "\n-------------------------------------\n")
for k,v in marking.items():
if v>=100:
present_students.append(k)
attendance_sheet.write(k+"\n")
attendance_sheet.close()
attendance_display=tk.Toplevel()
attendance_display.geometry("300x583+"+ str(self.window.winfo_x()+768) + "+" + str(self.window.winfo_y()))
try:
attendance_display.title("Attendance for "+ subject_now)
except:
attendance_display.title("Attendance Sheet")
label=""
for student in present_students:
label=label+"\n"+student
attendance_label=tk.Label(attendance_display,text=label)
attendance_label.pack()
def start_class(self):
self.train_model()
self.get_subject()
self.update()
def get_time(self):
time_now=int(dt.datetime.now().strftime("%H"))
if ((time_now <= 17) and (time_now >= 9)):
if(time_now>=12):
time_now=time_now%12
self.get_subject()
else:
self.get_subject()
def get_subject(self):
global subject_now
now=dt.datetime.today().weekday() #0 for monday, 6 for sunday
df = pd.read_excel("timetable/timetable.xlsx",engine='openpyxl')
hour_now=int(dt.datetime.now().strftime("%H"))
if ((int(hour_now)>12) and (int(hour_now)<=17)):
hour_now=hour_now%12
session="{} to {}".format(int(hour_now),int(hour_now)+1)
today_timetable=df.iloc[now]
subject_now=today_timetable[session]
if ((int(hour_now)<12 and="" hour_now="" int="">=9)):
today_timetable=df.iloc[now]
subject_now=today_timetable[session]
if (int(hour_now)==12):
session="{} to 1".format(int(hour_now))
today_timetable=df.iloc[now]
subject_now=today_timetable[session]
if((int(hour_now)>17) or (int(hour_now)<9 .format="" _="" __del__="" __init__="" add_student="" ake="" alg="haarfront.xml" ame="" app="" apture="" args.name="" args.type="" args="CommandLineParse().args" attendance="" avi="" bg="black" bold="" break="" cam.release="" cam="cv2.VideoCapture(0)" clearly="" command="lambda:" commandlineparse:="" completed="" count="" count_student="" create_database="" cv2.color_rgb2bgr="" cv2.cvtcolor="" cv2.destroyallwindows="" cv2.font_hershey_plain="" cv2.imread="" cv2.imshow="" cv2.imwrite="" cv2.puttext="" cv2.rectangle="" cv2.videowriter_fourcc="" d-="" datasets="" date="" dd="" def="" dirs:="" dirs="" dt.datetime.now="" elapsedtimeclock:="" else:="" esolution="" f="" face="gray[y:y+h,x:x+w]" face_cascade="cv2.CascadeClassifier(haar_file)" face_resize="cv2.resize(face,(width,height))" faces:="" faces="face_cascade.detectMultiScale(gray,1.3,4)" fg="white" filename="" files="" folder="self.student_enroll.get()" font="(" for="" frame="" get_all_student_names="" get_frame="" global="" gray="cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)" grayimg="cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)" h="" haar="cv2.CascadeClassifier(alg)" haar_file="haarfront.xml" height="" id="" ideo="" if="" images.append="" images="" img="" in="" int="" is="" k="" key="=27:" label="" labels.append="" labels="" lis="" m-="" main="" mark_student="" marking="" mart="" model.train="" model="cv2.face.LBPHFaceRecognizer_create()" mp4="" nable="" name="" name_stu="" names="" nargs="1,default=[" nknown="" no="" not="" nroll="" numpy.array="" o="" one="" onlyface="grayImg[y:y+h,x:x+w]" open="" os.listdir="" os.mkdir="" os.path.isdir="" os.walk="" p="" parent="students" parser.add_argument="" parser="argparse.ArgumentParser(description=" path="" pre="" prediction="" print="" raining="" raise="" res="" resizeimg="" ret:="" ret="" return="" row="1,column=0)" s-="" s.jpg="" s="" select="" self.args="parser.parse_args()" self.capture_pic.grid="" self.capture_pic="tk.Button(self.student_data_window,text=" self.check_subject="" self.count_student="" self.create_database="" self.elapsedtime="dt.datetime(1,1,1).now()-self.zeroTime" self.enroll_label.grid="" self.enroll_label="tk.Label(self.student_data_window,text=" self.fourcc="" self.get_all_student_names="" self.get_subject="" self.height="res" self.lasttime:="" self.lasttime="self.time2" self.mark_student="" self.name="" self.name_label.grid="" self.name_label="tk.Label(self.student_data_window,text=" self.now="dt.datetime(1,1,1).now()" self.out.release="" self.out="cv2.VideoWriter(path+" self.running:="" self.running="0" self.student="stu_name" self.student_data_window.destroy="" self.student_data_window.geometry="" self.student_data_window.title="" self.student_data_window="tk.Toplevel()" self.student_enroll.grid="" self.student_enroll="tk.Entry(self.student_data_window)" self.student_name.grid="" self.student_name="tk.Entry(self.student_data_window)" self.t.after_cancel="" self.t.config="" self.t.grid="" self.t="tk.Label(window,text=" self.tick="" self.time2="self.elapsedTime" self.upwin="" self.vid.isopened="" self.vid.release="" self.vid.set="" self.vid="cv2.VideoCapture(video_source)" self.width="" self.window.after="" self.window.winfo_x="" self.window.winfo_y="" self.zerotime="dt.datetime(1,1,1).now()-self.elapsedTime" self="" source="" start="" std_dimensions="{" stop="" str="" stu_name="" student="" student_list.append="" student_list="" subdir="" subject_now="Free-time" subjectpath="" sure="" system="" t="time.localtime()" text="self.time2)" that="" the="" tick="" time.strftime="" times="" tk.tk="" to="" train_model="" type="str,help=" unknown="" utput="" valueerror="" video="" video_source="" video_types="{" videocapture:="" visible="" w="" while="" width="" window="" x-10="" x200="" x="" y-10="" y="" your="">9>12>