Docfile commited on
Commit
7bd3c9a
1 Parent(s): 21c8775

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ import numpy as np
4
+ import cv2
5
+ import face_recognition
6
+ import os
7
+
8
+ # Load images for face recognition
9
+ Images = []
10
+ classnames = []
11
+ directory = "photos"
12
+
13
+ myList = os.listdir(directory)
14
+
15
+ for cls in myList:
16
+ if os.path.splitext(cls)[1] in [".jpg", ".jpeg"]:
17
+ img_path = os.path.join(directory, cls)
18
+ curImg = cv2.imread(img_path)
19
+ Images.append(curImg)
20
+ classnames.append(os.path.splitext(cls)[0])
21
+
22
+ def findEncodings(Images):
23
+ encodeList = []
24
+ for img in Images:
25
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
26
+ encode = face_recognition.face_encodings(img)[0]
27
+ encodeList.append(encode)
28
+ return encodeList
29
+
30
+ encodeListknown = findEncodings(Images)
31
+
32
+ # Function for face recognition
33
+ def recognize_faces(img):
34
+ image = np.array(img)
35
+ imgS = cv2.resize(image, (0, 0), None, 0.25, 0.25)
36
+ imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
37
+ facesCurFrame = face_recognition.face_locations(imgS)
38
+ encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
39
+
40
+ name = "Unknown" # Default name for unknown faces
41
+
42
+ if len(encodesCurFrame) > 0:
43
+ for encodeFace, faceLoc in zip(encodesCurFrame, facesCurFrame):
44
+ matches = face_recognition.compare_faces(encodeListknown, encodeFace)
45
+ faceDis = face_recognition.face_distance(encodeListknown, encodeFace)
46
+ matchIndex = np.argmin(faceDis)
47
+
48
+ if matches[matchIndex]:
49
+ name = classnames[matchIndex].upper()
50
+
51
+ y1, x2, y2, x1 = faceLoc
52
+ y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
53
+ cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
54
+ cv2.rectangle(image, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
55
+ cv2.putText(image, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
56
+
57
+ return image
58
+
59
+ # Create Gradio interface
60
+ iface = gr.Interface(
61
+ fn=recognize_faces,
62
+ inputs="image",
63
+ outputs="image",
64
+ live=True,
65
+ capture_session=True,
66
+ interpretation="default",
67
+ title="Face Recognition App",
68
+ description="This app recognizes faces in an image and updates attendance."
69
+ )
70
+
71
+ iface.launch()