Spaces:
Runtime error
Runtime error
Shafeek Saleem commited on
Commit ·
2736c78
1
Parent(s): e87299f
implemented face recognition
Browse filesFiles changed (2)
6 unmodified lines78910111248 unmodified lines616263646566676 unmodified linesimport timeimport face_recognitionimport jsoninitialize_login()initialize_level()48 unmodified linesface_image = face_recognition.load_image_file(os.path.join(img_dir, img))my_face_encoding = face_recognition.face_encodings(face_image)my_bar.progress(int((i + 1) / len(images) * 100), text="Generating face encodings...")with open(os.path.join(".sessions", get_login()["username"], img.split("_")[1]+".npy"), 'wb') as f:np.save(f, my_face_encoding)# face_encodings_dict[img.split("_")[1]] = my_face_encoding.tolist()my_bar.progress(100, text="Successfully encoded all the known faces!")6 unmodified lines7891011121348 unmodified lines626364656667686 unmodified linesimport timeimport face_recognitionimport jsonimport numpy as npinitialize_login()initialize_level()48 unmodified linesface_image = face_recognition.load_image_file(os.path.join(img_dir, img))my_face_encoding = face_recognition.face_encodings(face_image)my_bar.progress(int((i + 1) / len(images) * 100), text="Generating face encodings...")with open(os.path.join(".sessions", get_login()["username"], "face_encodings",img.split("_")[1]+".npy"), 'wb') as f:np.save(f, my_face_encoding)# face_encodings_dict[img.split("_")[1]] = my_face_encoding.tolist()my_bar.progress(100, text="Successfully encoded all the known faces!")
3 unmodified lines45678910 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576773 unmodified linesfrom utils.inference import queryimport osimport timeinitialize_login()initialize_level()10 unmodified linesfor item in output:st.progress(item["score"], text=item["label"])def step4_page():st.header("Trying It Out")st.markdown("""### How Our Emotion Detection Application WorksNow that we have trained our emotion detection application, let's see how it works in action! Here's a simple explanation of how the application recognizes emotions:1. **Looking at Faces**: When we use our emotion detection application, we can show it a picture of a face or use a camera to capture a real-time image. It's like giving our application a chance to see someone's expression.2. **Observing the Features**: The application carefully looks at the face and pays attention to different parts, like the eyes, mouth, and eyebrows. It tries to understand the expressions by noticing how these parts look and how they are positioned. It's like the application is taking a close look at the face, just like we do when we try to understand someone's emotions.""")st.image("https://camo.githubusercontent.com/3bb4e2eba7c8a91d71916496bc775e870222f19bb5098cb4bc514ed60078c1e7/68747470733a2f2f626c6f672e7161746573746c61622e636f6d2f77702d636f6e74656e742f75706c6f6164732f323032302f30312f4d4c5f6578616d706c652e6769663f7261773d74727565",use_column_width=True,)st.markdown("""3. **Guessing the Emotion**: Based on what it observed, our application uses the knowledge it learned during training to make its best guess about the person's emotion. It remembers the patterns it saw before and tries to match them with the features it observed. It might think the person looks happy, sad, or maybe surprised!""")st.image("https://miro.medium.com/v2/resize:fit:1358/1*KoHwRNZGrVrhdbye3BDEew.png",use_column_width=True,)st.markdown("""4. **Providing a Result**: Finally, our emotion detection application tells us what emotion it thinks the person is feeling. It might say, "I think this person looks happy!" or "I think this person looks sad." It's like having a virtual friend who can give us their guess about someone's emotion.By going through these steps, our emotion detection application can quickly analyze faces and give us an idea of how someone might be feeling. It's like having a special friend who can understand and guess emotions based on facial expressions!""")st.info("Now that we know how our emotion detection application works, let's try it out!")st.info("Select an image to analyze!")input_type = st.radio("Select the Input Type", ["Image", "Camera"])if input_type == "Camera":image = st.camera_input("Take a picture")byte_image = image.getvalue() if image else Noneelse:image = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])byte_image = image.read() if image else Nonetry_img = os.path.join(".sessions", get_login()["username"], "try.jpg")if byte_image:with open(try_img, "wb") as f:f.write(byte_image)infer(try_img)st.info("Click on the button below to complete this level!")if st.button("Complete Level"):3 unmodified lines45678910111210 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192933 unmodified linesfrom utils.inference import queryimport osimport timeimport face_recognitionimport cv2import numpy as npinitialize_login()initialize_level()10 unmodified linesfor item in output:st.progress(item["score"], text=item["label"])# Get a reference to webcam #0 (the default one)video_capture = cv2.VideoCapture(0)def step4_page():st.header("Trying It Out")st.info("Now that we know how our face recognition application works, let's try it out!")face_encodings_dir = os.path.join(".sessions", get_login()["username"], "face_encodings")face_encodings = os.listdir(face_encodings_dir)known_face_encodings = []known_face_names = []if len(face_encodings) > 0:for i, face_encoding in enumerate(face_encodings):with open(os.path.join(face_encodings_dir, face_encoding), 'rb') as f:known_face_encoding = np.load(f)face_name = img.split(".")[0]known_face_encodings.append(known_face_encoding)known_face_names.append(face_name)while True:# Grab a single frame of videoret, frame = video_capture.read()# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)rgb_frame = frame[:, :, ::-1]# Find all the faces and face encodings in the frame of videoface_locations = face_recognition.face_locations(rgb_frame)face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)# Loop through each face in this frame of videofor (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):# See if the face is a match for the known face(s)matches = face_recognition.compare_faces(known_face_encodings, face_encoding)name = "Unknown"# If a match was found in known_face_encodings, just use the first one.# if True in matches:# first_match_index = matches.index(True)# name = known_face_names[first_match_index]# Or instead, use the known face with the smallest distance to the new faceface_distances = face_recognition.face_distance(known_face_encodings, face_encoding)best_match_index = np.argmin(face_distances)if matches[best_match_index]:name = known_face_names[best_match_index]# Draw a box around the facecv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)# Draw a label with a name below the facecv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)font = cv2.FONT_HERSHEY_DUPLEXcv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)# Display the resulting imagecv2.imshow('Video', frame)# Hit 'q' on the keyboard to quit!if cv2.waitKey(1) & 0xFF == ord('q'):break# Release handle to the webcamvideo_capture.release()cv2.destroyAllWindows()st.info("Click on the button below to complete this level!")if st.button("Complete Level"):
pages/3_Face Encodings.py+2-1
pages/4_Face Recognition.py+60-44