Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 699fa50

Browse files
Update lockScreen.py
1 parent aaec4b2 commit 699fa50

File tree

1 file changed

+83
-68
lines changed

1 file changed

+83
-68
lines changed
Lines changed: 83 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,101 +1,112 @@
1-
import tkinter as tk
1+
import tkinter as tk#Used to make GUI and fullscreen lock-screen
22
import numpy as np
33
import cv2
44
from PIL import Image, ImageTk
5-
import face_recognition
6-
from Utils import Blocking
5+
import face_recognition#Library Used for Face Recognition
6+
from Utils import Blocking#To Block Keyboard and Mouse Temporarily
77
from PIL import ImageTk as itk
8-
from win32api import GetSystemMetrics
9-
from gtts import gTTS
8+
from win32api import GetSystemMetrics# To get resolution of monitor
9+
from gtts import gTTS# Text to Speech
1010
from io import BytesIO
11-
import playsound
11+
import playsound# Play Sound
1212
import os
13-
import winsound
13+
import winsound# To play background music
1414

1515
bg = "Images/bg.jpg"
16-
bgmusic = 'Images/bluedanube.wav'
16+
bgmusic = 'Images/bluedanube.wav'# These two are default wallpaper and music
1717

18+
# Asking User whether they wish to use customization
1819
customizeOrNot = input("Press \'Y\' or \'y\' if you wish to customize background music and wallpaper \n")
1920
if customizeOrNot.lower() == 'y':
2021
bg = "Images/"+input("Enter filename of wallpaper : ")
2122
bgmusic = "Images/"+input("Enter filename of music file (WAV only) : ")
2223

23-
name=input("Please Enter First Name Entered During Registration: ")
24-
#if name+"png" in
25-
2624

25+
# This name variable is used to get original picture of user generated using faceRegister module
26+
name=input("Please Enter First Name Entered During Registration: ")
2727

2828
length=""
2929

3030

31+
# We are using try and except block to make sure that if user enters wrong Name (One that doesn't exists in faceRegister Folder) program is terminated.
3132
try:
3233
img = face_recognition.load_image_file(f'Utils/faceRegister/{name}.png')
3334
#Blocking.blockinput()
3435
except:
3536
print("Incorrect User Name")
3637
exit()
37-
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
38-
faceLoc = face_recognition.face_locations(img)[0]
39-
encodeImg = face_recognition.face_encodings(img)[0]
40-
cv2.rectangle(img,(faceLoc[3],faceLoc[0]),(faceLoc[1],faceLoc[2]),(255,0,255),2)
4138

39+
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) # Loading Orignal Image in img variable
40+
faceLoc = face_recognition.face_locations(img)[0] # Using Face Recognition library to get face locations
41+
encodeImg = face_recognition.face_encodings(img)[0] # We are then encoding it so that afterwards we can compare
42+
cv2.rectangle(img,(faceLoc[3],faceLoc[0]),(faceLoc[1],faceLoc[2]),(255,0,255),2) # Just to display purple rectangle
4243

44+
# To terminate Tkinter GUI
4345
def quit():
4446
root.destroy()
4547

46-
root=tk.Tk()
48+
root=tk.Tk()# Defining Window
4749
#root.config(background="#FFFFFF")
4850

4951

50-
image=Image.open(bg)
51-
image = image.resize((GetSystemMetrics(0), GetSystemMetrics(1)), Image.ANTIALIAS)
52+
image=Image.open(bg)# Background Image
53+
image = image.resize((GetSystemMetrics(0), GetSystemMetrics(1)), Image.ANTIALIAS)# To get resolution of monitor for wallpaper
5254
bg = itk.PhotoImage(image)
53-
label1 = tk.Label(root, image = bg)
55+
label1 = tk.Label(root, image = bg)# Make A tkinter Label and put the image into that label and place it on origin
5456
label1.place(x = 0, y = 0)
5557

5658

5759
root.grid_columnconfigure(0, weight=1)
58-
root.attributes('-fullscreen', True)
59-
button = tk.Button(root, text = 'Quit', command=quit)
60+
root.attributes('-fullscreen', True)# Make the window fullscreen
61+
button = tk.Button(root, text = 'Quit', command=quit)# Button to close the window (Used during debugging)
6062
#button.grid(row=1,column=0,padx=10,pady=2)
61-
imageFrame = tk.Frame(root, width=600, height=500)
62-
imageFrame.grid(row=0, column=0, padx=10, pady=2)
63+
imageFrame = tk.Frame(root, width=600, height=500)# Make a frame to display webcam live capture
64+
imageFrame.grid(row=0, column=0, padx=10, pady=2)# Put it in topmost section with row no 0
6365

66+
# Just a label at below webcam
6467
l = tk.Label(root, text = "Processing... Screen is now Locked. You can't Access Keyboard or Mouse")
6568
l.config(font =("Courier", 14))
6669
l.grid(row=2, column=0, padx=10, pady=2)
6770

71+
# This Label Show live Status of Whether face is detected or no one is in front of screen or wrong person
6872
l2 = tk.Label(root, text = length)
6973
l2.config(font =("Sitka Text", 30))
7074
l2.config(bg = "#270057", fg='white')
7175
l2.grid(row=3, column=0, padx=10, pady=30)
7276

77+
# For displaying video Capture
7378
lmain = tk.Label(imageFrame)
7479
lmain.grid(row=0, column=0)
7580
cap = cv2.VideoCapture(0)
7681

77-
final_answer=""
78-
final_answer_list=[]
79-
counter=0
80-
counter2=0
82+
# These are few global variables that are change during execution
83+
final_answer="" # Correct or Incorrect Face
84+
final_answer_list=[] # This stores result of 10 iterations
85+
counter=0 # Counter of no of Trues in above list
86+
counter2=0 # To show number of Tests passed
8187

82-
flagNoone = 0
83-
flagWrong = 0
84-
flagCorrect = 0
88+
# These flags are used for sole purpose of voice and background music. These flags make sure that we are not re running the music
89+
flagNoone = 0 # Flag is on when no one is
90+
flagWrong = 0 # Flag is on when wrong person detected
91+
flagCorrect = 0 # Flag is on when correct person is detected
8592

93+
# This function is used to show live feed on tkinter window
8694
def show_frame():
87-
Blocking.blockinput()
88-
_, imgTest = cap.read()
95+
Blocking.blockinput()# Once reached this step block the keyboard and mouse
96+
_, imgTest = cap.read()# Just reading the frames from webcam
8997
imgTest = cv2.flip(imgTest, 1)
90-
imgTest = cv2.resize(imgTest, (0, 0), fx = 0.5, fy = 0.5)
91-
cv2image = cv2.cvtColor(imgTest, cv2.COLOR_BGR2RGBA)
92-
img = Image.fromarray(cv2image)
98+
imgTest = cv2.resize(imgTest, (0, 0), fx = 0.5, fy = 0.5)# Resizing Image to 50%
99+
cv2image = cv2.cvtColor(imgTest, cv2.COLOR_BGR2RGBA)#To RGBA
100+
img = Image.fromarray(cv2image)# Using PIL to convert it into compatible image
93101
imgtk = ImageTk.PhotoImage(image=img)
94-
lmain.imgtk = imgtk
102+
lmain.imgtk = imgtk# Putting image on the Label
95103
lmain.configure(image=imgtk)
96-
lmain.after(10, detect)
97-
104+
lmain.after(10, detect) # Go to detect Function
105+
106+
# Function used to detect the face
98107
def detect():
108+
# All global variables
109+
99110
global length, l2, final_answer,final_answer_list, counter, counter2, flagNoone, flagWrong, flagCorrect, bgmusic
100111

101112
#Blocking.blockinput()
@@ -109,46 +120,48 @@ def detect():
109120
lmain.imgtk = imgtk
110121
lmain.configure(image=imgtk)
111122
lmain.after(10, show_frame)
112-
123+
124+
# Try and Except to Check if user is in front of screen or not. If not then it will throw exception and we have to catch that
113125
try:
114126
#Blocking.blockinput()
115-
faceLocTest = face_recognition.face_locations(imgTest)[0]
116-
encodeTest = face_recognition.face_encodings(imgTest)[0]
127+
faceLocTest = face_recognition.face_locations(imgTest)[0]# Getting face locations of webcam Image just like we did before for original Image
128+
encodeTest = face_recognition.face_encodings(imgTest)[0]# Encoding it
117129
cv2.rectangle(imgTest,(faceLocTest[3],faceLocTest[0]),(faceLocTest[1],faceLocTest[2]),(255,0,255),2)
118130
#results = face_recognition.compare_faces([encodeImg],encodeTest)
119-
faceDis = face_recognition.face_distance([encodeImg],encodeTest)
131+
faceDis = face_recognition.face_distance([encodeImg],encodeTest)# This is used to calculate the distance between the original and webcam image
120132
#print(results,faceDis)
121133
cv2.putText(imgTest,f'{faceDis[0]}',(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,0,255),2)
122-
if faceDis[0]<=0.4:
123-
flagNoone = 0
124-
flagWrong = 0
125-
winsound.PlaySound(None, winsound.SND_FILENAME)
134+
if faceDis[0]<=0.4:# Here we are checking that if distance is less than 0.4 which can be also understood as whether the confidence level of Image being same is greater than 60 % or not (less distance more confidence)
135+
flagNoone = 0# We are in Correct Image Detected so flag no one is 0
136+
flagWrong = 0# We are in Correct Image Detected so flag wrong one is 0
137+
winsound.PlaySound(None, winsound.SND_FILENAME)# Don't Play any music (music is only played when no face is detected). We can just play None to mute it.
126138
#print(faceDis[0])
127139
#print(faceDis[0]<=0.4)
128-
final_answer=True
140+
final_answer=True# If confidence level is greater than 60% faces match and append the result in list
129141
final_answer_list.append(final_answer)
130-
counter2=counter2+1
131-
l2.config(text=f'{counter2} test passed ✔')
142+
counter2=counter2+1# We are incrementing it to print value in below line
143+
l2.config(text=f'{counter2} test passed ✔')# Dynamically change status label on GUI
132144

133145
if flagCorrect == 0:
134-
msg = "Stay Still. Minimum 8 Cases should pass"
146+
msg = "Stay Still. Minimum 8 Cases should pass"# Message to be spoken by Gtts
135147
myobj = gTTS(text=msg, lang='en', slow = 'False')
136148

137149
try:
138-
os.remove('msg.mp4')
150+
os.remove('msg.mp4')# If for any reason this file exists remove it first and if it throws error simply print it
139151
except Exception as e:
140152
print(e)
141153

142-
myobj.save('msg.mp4')
143-
playsound.playsound('msg.mp4')
144-
os.remove('msg.mp4')
145-
flagCorrect = 1
154+
myobj.save('msg.mp4') # Save audio file
155+
playsound.playsound('msg.mp4') # Play it
156+
os.remove('msg.mp4') # remove it
157+
flagCorrect = 1 # Now setting Flag correct as 1, if flag is not 1 then sound will keep on playing
158+
# What is confidence is less than 60%
146159
else:
147-
final_answer=False
148-
final_answer_list.append(final_answer)
160+
final_answer=False# Answer becomes false
161+
final_answer_list.append(final_answer)# append to global list
149162
#counter2=0
150-
l2.config(text="❌Wrong Person❌")
151-
winsound.PlaySound(None, winsound.SND_FILENAME)
163+
l2.config(text="❌Wrong Person❌")# Dynamically change status label on GUI
164+
winsound.PlaySound(None, winsound.SND_FILENAME)# Same like before dont play music
152165
flagNoone = 0
153166
flagCorrect = 0
154167

@@ -164,14 +177,14 @@ def detect():
164177
myobj.save('msg.mp4')
165178
playsound.playsound('msg.mp4')
166179
os.remove('msg.mp4')
167-
flagWrong = 1
168-
180+
flagWrong = 1 # Above lines are same like before
169181

170182

183+
# Exception occurs when no one is in front of screen since we have no another image to compare
171184
except Exception as e:
172185
#Blocking.blockinput()
173186

174-
l2.config(text="❖ No one is in front of the Screen. Screen is Locked ❖")
187+
l2.config(text="❖ No one is in front of the Screen. Screen is Locked ❖")# Dynamically change status label on GUI
175188
#counter2=0
176189
print(e)
177190
#msg = "Wrong Person Detected"
@@ -184,10 +197,10 @@ def detect():
184197
flagCorrect = 0
185198

186199
if flagNoone == 0:
187-
winsound.PlaySound(bgmusic, winsound.SND_ALIAS | winsound.SND_ASYNC)
200+
winsound.PlaySound(bgmusic, winsound.SND_ALIAS | winsound.SND_ASYNC)# Here we are playing music and passing bgmusic as parameter instead of none
188201
flagNoone=1
189202

190-
203+
# This block runs every time
191204
finally:
192205
#Blocking.blockinput()
193206

@@ -198,17 +211,19 @@ def detect():
198211
#cv2.imshow('Original',img)
199212
#print(final_answer)
200213
print(final_answer_list)
214+
# When length of the global answer list becomes greater than 10 do this
201215

202216
if len(final_answer_list)>10:
203217

204-
for ele in final_answer_list:
218+
for ele in final_answer_list:# Check no of Trues in list
205219
if ele==True:
206220
counter=counter+1
207-
if counter/len(final_answer_list) >0.8:
221+
if counter/len(final_answer_list) >0.8:# If its greater than 80 % then Unblock the Keyboard and Mouse and Run Quit function
208222
print("Accuracy",counter/len(final_answer_list))
209-
Blocking.unblockinput()
223+
Blocking.unblockinput()# Reenable inputs
210224
quit()
211225
else:
226+
# Else we will simply set counters back to 0 and loop again
212227
print(counter/len(final_answer_list))
213228
final_answer_list=[]
214229
counter=0
@@ -218,5 +233,5 @@ def detect():
218233

219234

220235
show_frame()
221-
root.mainloop()
236+
root.mainloop()# To Run GUI
222237

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /