-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2_face_recognition.py
More file actions
198 lines (172 loc) · 5.42 KB
/
2_face_recognition.py
File metadata and controls
198 lines (172 loc) · 5.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import cv2
import numpy as np
import RPi.GPIO as GPIO
import os
import sys
import threading
from time import *
from lcd import *
from progress.bar import *
import tkinter as tk
# Declaration of pin
pinGreenLed=5
pinRedLed=4
pinYellowLed=26
pinBeep=17
pinBtn=13
pinMagnes=6
pinSensor=19
#Setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(pinGreenLed, GPIO.OUT)
GPIO.setup(pinRedLed, GPIO.OUT)
GPIO.setup(pinYellowLed, GPIO.OUT)
GPIO.setup(pinBtn, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(pinMagnes, GPIO.OUT)
GPIO.setup(pinSensor,GPIO.IN, GPIO.PUD_UP)
def beep(counter):
GPIO.setup(pinBeep, GPIO.OUT)
GPIO.output(pinBeep, GPIO.LOW)
sleep(counter)
GPIO.output(pinBeep, GPIO.HIGH)
GPIO.setup(pinBeep,GPIO.IN)
def openDoor(getout,ev=None):
global lcd
lcd = LCD()
# Open door
lcd.clear()
GPIO.output(pinRedLed, GPIO.HIGH)
GPIO.output(pinGreenLed, GPIO.LOW)
GPIO.output(pinMagnes, GPIO.HIGH)
beep(0.5)
for x in range(1,11):
time = 11-x
if getout == False :
lcd.message("Hello: %s\nRemaining: %dsec"%(str(id),time))
else :
lcd.clear()
lcd.message("Open doors\nRemaining: %dsec"%(time))
sleep(1)
lcd.clear()
# Close door
if(GPIO.input(pinSensor)):
flaga = True;
while(GPIO.input(pinSensor)):
if(flaga):
GPIO.output(pinYellowLed, GPIO.HIGH)
lcd.message("CLOSE THE DOOR")
flaga = False
GPIO.output(pinYellowLed, GPIO.LOW)
lcd.clear()
lcd.message("CLOSED")
GPIO.output(pinGreenLed, GPIO.HIGH)
GPIO.output(pinRedLed, GPIO.LOW)
GPIO.output(pinMagnes, GPIO.LOW)
beep(0.5)
def loader():
sizeTrainer = int(os.path.getsize('trainer/trainer.yml')/(1024*1024))
timeToLoad = int(sizeTrainer/4.3)
bar = FillingSquaresBar('Starting the system', max=timeToLoad,suffix='%(percent)d%%')
for i in range(timeToLoad):
sleep(1)
bar.next()
bar.finish()
#=====================
# System starts
recognizer = cv2.face.LBPHFaceRecognizer_create()
def readTrainer():
recognizer.read('trainer/trainer.yml')
t1=threading.Thread(target=readTrainer,args=())
t2=threading.Thread(target=loader,args=())
t1.start()
t2.start()
t1.join()
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
font = cv2.FONT_HERSHEY_SIMPLEX
# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)
if not cam.isOpened():
print("Error: Camera is already opened.")
exit()
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#cam.set(3, screen_width) # set video widht
#cam.set(4, screen_height) # set video height
cam.set(3, 640) # set video widht
cam.set(4, 480) # set video height
# Define min window size to be recognized as a face
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)
# Initialization of the variable to check the face several times
incToOpen=0
openOnInc=5
# Iniciate id counter
id = 0
# Names related to id
names = ['None']
# List of avalible users
FileFaceNamePath = os.path.abspath('name_dataset')
ifExistsFileFaceName = os.path.isfile(FileFaceNamePath)
if ifExistsFileFaceName:
print("\nList of user in dataset:")
print("ID| NAME")
faceNameFileRead = open(FileFaceNamePath,"r")
if faceNameFileRead.mode == 'r':
contents = faceNameFileRead.read()
print(contents)
# Searching of new face ID
faceNameFileRead.seek(0)
for line in faceNameFileRead.readlines() :
name = line.split("|")[1]
names.append(name.split("\n")[0])
faceNameFileRead.close()
while True:
if(GPIO.input(pinBtn)== 0):
openDoor(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)
id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
# Check if confidence is less them 100 ==> "0" is perfect match
if (confidence < 100):
id = names[id]
recognitionPercent=int(100-confidence)
confidence = " {0}%".format(round(100 - confidence))
if recognitionPercent>60:
incToOpen+=1
print("Percentage of recognition: %d"%recognitionPercent)
print("The flag to open: %d"%incToOpen)
else:
id = "unknown"
confidence = " {0}%".format(round(100 - confidence))
incToOpen=0
#Adding text to rectengle (Object, string, position, font, size, color, fontThickness)
cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
cv2.putText(img, "Check:"+str(incToOpen)+"/"+str(openOnInc), (x+10,y+h-5), font, 1, (0,255,255), 1)
cv2.putText(img, str(confidence), (x+170,y+h-5), font, 1, (255,255,0), 1)
if(incToOpen==openOnInc):
openDoor(False)
incToOpen=0
#cv2.namedWindow('Monitoring', cv2.WND_PROP_FULLSCREEN)
#cv2.setWindowProperty('Monitoring',cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
cv2.imshow('Monitoring',img)
k = cv2.waitKey(10) & 0xff
if k == 27: # Press 'ESC' for exit program
break
if k == 32: # Press 'Space' to open door
openDoor(True)
# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
GPIO.cleanup()