nikshep01 commited on
Commit
5fec869
·
verified ·
1 Parent(s): 6c5f0dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -34
app.py CHANGED
@@ -1,47 +1,99 @@
1
  import streamlit as st
2
  from PIL import Image
3
- import torch
4
- from torchvision import transforms
5
- from transformers import pipeline
 
 
6
 
7
- # Load the face detection model
8
- face_detector = pipeline('face-detection', model='facebook/facemask-plugin-fasterrcnn')
9
 
10
- # Function to detect faces in an image
11
- def detect_faces(image):
12
- # Convert image to PyTorch tensor
13
- image_tensor = transforms.ToTensor()(image).unsqueeze(0)
 
14
 
15
- # Detect faces
16
- faces = face_detector(image_tensor)
 
 
 
 
 
 
17
 
18
- return faces
 
19
 
20
- # Streamlit app
21
- def main():
22
- st.title("Multiple Face Detection using Hugging Face")
23
 
24
- uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
 
 
 
 
 
 
25
 
26
- if uploaded_file is not None:
27
- # Read the image
28
- image = Image.open(uploaded_file)
29
- st.image(image, caption="Uploaded Image", use_column_width=True)
30
 
31
- # Detect faces
32
- faces = detect_faces(image)
33
 
34
- # Display the number of faces detected
35
- num_faces = len(faces)
36
- st.write(f"Number of faces detected: {num_faces}")
37
 
38
- # Display bounding boxes around detected faces
39
- for face in faces:
40
- xmin, ymin, xmax, ymax = face['box']
41
- image_with_box = image.copy()
42
- draw = ImageDraw.Draw(image_with_box)
43
- draw.rectangle([xmin, ymin, xmax, ymax], outline="red", width=3)
44
- st.image(image_with_box, caption="Face Detection", use_column_width=True)
45
 
46
- if __name__ == "__main__":
47
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from PIL import Image
3
+ import face_recognition
4
+ import cv2
5
+ import numpy as np
6
+ import os
7
+ from datetime import datetime
8
 
9
+ st.title("AIMLJan24 - Face Recognition")
 
10
 
11
+ # Load images for face recognition
12
+ Images = []
13
+ classnames = []
14
+ directory = "photos"
15
+ myList = os.listdir(directory)
16
 
17
+ st.write("Photographs found in folder : ")
18
+ for cls in myList:
19
+ if os.path.splitext(cls)[1] in [".jpg", ".jpeg"]:
20
+ img_path = os.path.join(directory, cls)
21
+ curImg = cv2.imread(img_path)
22
+ Images.append(curImg)
23
+ st.write(os.path.splitext(cls)[0])
24
+ classnames.append(os.path.splitext(cls)[0])
25
 
26
+ # Load images for face recognition
27
+ encodeListknown = [face_recognition.face_encodings(img)[0] for img in Images]
28
 
29
+ # camera to take photo of user in question
30
+ file_name = st.file_uploader("Upload image")
 
31
 
32
+ def add_attendance(name):
33
+ username = name
34
+ current_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
35
+ print(current_datetime)
36
+
37
+ if not os.path.isdir('Attendance'):
38
+ os.makedirs('Attendance')
39
 
40
+ if f'Attendance-{current_datetime}.csv' not in os.listdir('Attendance'):
41
+ with open(f'Attendance/Attendance-{current_datetime}.csv', 'w') as f:
42
+ f.write('Name,Time')
43
+
44
 
45
+ if file_name is not None:
46
+ col1, col2 = st.columns(2)
47
 
48
+ test_image = Image.open(file_name)
49
+ image = np.asarray(test_image)
 
50
 
51
+ imgS = cv2.resize(image, (0, 0), None, 0.25, 0.25)
52
+ imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
53
+ facesCurFrame = face_recognition.face_locations(imgS)
54
+ encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
 
 
 
55
 
56
+ # List to store recognized names for all faces in the image
57
+ recognized_names = []
58
+
59
+ # Checking if faces are detected
60
+ if len(encodesCurFrame) > 0:
61
+ for encodeFace, faceLoc in zip(encodesCurFrame, facesCurFrame):
62
+ # Assuming that encodeListknown is defined and populated in your code
63
+ matches = face_recognition.compare_faces(encodeListknown, encodeFace)
64
+ faceDis = face_recognition.face_distance(encodeListknown, encodeFace)
65
+
66
+ # Initialize name as Unknown
67
+ name = "Unknown"
68
+
69
+ # Check if there's a match with known faces
70
+ if True in matches:
71
+ matchIndex = np.argmin(faceDis)
72
+ name = classnames[matchIndex].upper()
73
+
74
+ # Append recognized name to the list
75
+ recognized_names.append(name)
76
+
77
+ # Draw rectangle and label on the image
78
+ y1, x2, y2, x1 = faceLoc
79
+ y1, x2, y2, x1 = (y1 * 4), (x2 * 4), (y2 * 4) ,(x1 * 4)
80
+
81
+ # Make a copy of the image array before drawing on it
82
+ image_copy = image.copy()
83
+
84
+ cv2.rectangle(image_copy, (x1, y1), (x2, y2), (0, 255, 0), 2)
85
+ cv2.rectangle(image_copy, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
86
+ cv2.putText(image_copy, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
87
+
88
+ # Update the database
89
+ add_attendance(name)
90
+
91
+ # Display the image with recognized names
92
+ st.image(image_copy, use_column_width=True, output_format="PNG")
93
+
94
+ # Display recognized names
95
+ st.write("Recognized Names:")
96
+ for i, name in enumerate(recognized_names):
97
+ st.write(f"Face {i+1}: {name}")
98
+ else:
99
+ st.warning("No faces detected in the image. Face recognition failed.")