Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
import numpy as np
|
3 |
+
import cv2
|
4 |
+
import face_recognition
|
5 |
+
import streamlit as st
|
6 |
+
|
7 |
+
p1 = "raavi.jpg"
|
8 |
+
p2 = "jivan.jpg"
|
9 |
+
|
10 |
+
st.title("Face Recognition")
|
11 |
+
Images = []
|
12 |
+
classnames = []
|
13 |
+
|
14 |
+
# Read images and train the face_recognition package
|
15 |
+
img1 = cv2.imread(p1)
|
16 |
+
Images.append(img1)
|
17 |
+
classnames.append("Ravi")
|
18 |
+
|
19 |
+
img2 = cv2.imread(p2)
|
20 |
+
Images.append(img2)
|
21 |
+
classnames.append("Jivan")
|
22 |
+
|
23 |
+
# Load images for face recognition
|
24 |
+
encodeListknown = [face_recognition.face_encodings(img)[0] for img in Images]
|
25 |
+
|
26 |
+
# Take image from user
|
27 |
+
img_file_buffer = st.camera_input("Take a picture")
|
28 |
+
|
29 |
+
# Recognise the face in the uploaded image
|
30 |
+
if img_file_buffer is not None:
|
31 |
+
test_image = Image.open(img_file_buffer)
|
32 |
+
# Convert to NumPy array and create a writeable copy
|
33 |
+
image = np.array(test_image)
|
34 |
+
image = image.copy() # Create a writeable copy of the image array
|
35 |
+
|
36 |
+
imgS = cv2.resize(image, (0, 0), None, 0.25, 0.25)
|
37 |
+
imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
|
38 |
+
facesCurFrame = face_recognition.face_locations(imgS)
|
39 |
+
encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
|
40 |
+
faceMatchedflag = 0
|
41 |
+
|
42 |
+
# Loop to find match in encodeListknown
|
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 |
+
st.write(name)
|
51 |
+
# Show the name on the image
|
52 |
+
y1, x2, y2, x1 = faceLoc
|
53 |
+
y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
|
54 |
+
|
55 |
+
# Draw rectangle around the face
|
56 |
+
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
57 |
+
# Optionally draw name label below face (commented out for now)
|
58 |
+
# cv2.rectangle(image , (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
|
59 |
+
# cv2.putText(image , name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
|
60 |
+
|
61 |
+
# Display image with the overlay
|
62 |
+
st.image(image, use_column_width=True, output_format="PNG")
|
63 |
+
faceMatchedflag = 1
|
64 |
+
|
65 |
+
if faceMatchedflag == 0:
|
66 |
+
st.warning("No faces detected in the image.")
|