Kosal Ang
Thu Aug 22 2024
In this article, we'll explore how to build a real-time face recognition system using Python, OpenCV, and the face_recognition
library. This project leverages powerful machine learning algorithms to identify and label faces in a video feed. The complete code is provided below, along with a detailed explanation of how it works.
1pip install opencv-python face-recognition numpy 2
Here's the complete code for the face recognition system:
1import face_recognition 2import cv2 3import numpy as np 4 5# Initialize the webcam 6video_capture = cv2.VideoCapture(0) 7 8# Load and encode known faces 9kosal_image = face_recognition.load_image_file("kosal.jpg") 10kosal_face_encoding = face_recognition.face_encodings(kosal_image)[0] 11 12lika_image = face_recognition.load_image_file("lika.jpg") 13lika_face_encoding = face_recognition.face_encodings(lika_image)[0] 14 15# Store the encodings and corresponding names in arrays 16known_face_encodings = [ 17 kosal_face_encoding, 18 lika_face_encoding, 19] 20known_face_names = [ 21 "Kosal", 22 "Molika", 23] 24 25# Initialize variables for face recognition 26face_locations = [] 27face_encodings = [] 28face_names = [] 29process_this_frame = True 30 31while True: 32 # Capture a frame from the webcam 33 ret, frame = video_capture.read() 34 35 if not ret: 36 print("Failed to grab frame") 37 break 38 39 # Process every other frame for performance 40 if process_this_frame: 41 # Resize the frame to 1/4 for faster processing 42 small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) 43 44 # Convert BGR image to RGB 45 rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB) 46 47 # Detect faces and get encodings 48 face_locations = face_recognition.face_locations(rgb_small_frame) 49 face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) 50 51 face_names = [] 52 for face_encoding in face_encodings: 53 # Check if the face matches any known faces 54 matches = face_recognition.compare_faces(known_face_encodings, face_encoding) 55 name = "Unknown" 56 57 # Find the closest match 58 face_distances = face_recognition.face_distance(known_face_encodings, face_encoding) 59 best_match_index = np.argmin(face_distances) 60 if matches[best_match_index]: 61 name = known_face_names[best_match_index] 62 63 face_names.append(name) 64 65 process_this_frame = not process_this_frame 66 67 # Draw boxes around faces and label them 68 for (top, right, bottom, left), name in zip(face_locations, face_names): 69 # Scale the coordinates back to the original size 70 top *= 4 71 right *= 4 72 bottom *= 4 73 left *= 4 74 75 # Draw a box around the face 76 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) 77 78 # Label the face with a name 79 cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) 80 font = cv2.FONT_HERSHEY_DUPLEX 81 cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) 82 83 # Display the video feed 84 cv2.imshow('Video', frame) 85 86 # Break the loop on 'q' key press 87 if cv2.waitKey(1) & 0xFF == ord('q'): 88 break 89 90# Release the webcam and close windows 91video_capture.release() 92cv2.destroyAllWindows() 93
cv2.VideoCapture(0)
.kosal.png
and lika.jpg
) are loaded and encoded using the face_recognition
library. These encodings are stored in arrays, which will be used to compare faces detected in the video feed.face_recognition.face_locations()
method. It then computes face encodings for the detected faces and compares them with the known encodings.Building a real-time face recognition system using Python, OpenCV, and face_recognition
is both straightforward and powerful. With minimal code, you can create applications that can recognize and label faces in real time. This system can be extended to recognize more faces by adding additional face encodings and names to the arrays.
This project is a great starting point for anyone interested in computer vision and machine learning. It demonstrates how easily these technologies can be integrated into practical applications.
References:
Unlock the full potential of Python development with our comprehensive guide on creating and using virtual environments
Learn how to enhance your real-time chat application built with Flask and Socket.IO by displaying the Socket ID of the message sender alongside each message. With this feature, you can easily identify the owner of each message in the chat interface, improving user experience and facilitating debugging. Follow this step-by-step tutorial to integrate Socket ID display functionality into your chat application, empowering you with deeper insights into message origins.
Asynchronous programming with asyncio in Python allows you to write concurrent code that can handle multiple tasks concurrently, making it particularly useful for I/O-bound operations like web scraping
Unlock the full potential of Python for data visualization with Matplotlib. This comprehensive guide covers everything you need to know to create stunning visualizations, from basic plotting to advanced customization techniques.
Web authentication is a vital aspect of web development, ensuring that only authorized users can access protected resources. Flask, a lightweight web framework for Python, provides Flask-Login
Learn how to handle Excel files effortlessly in Python using the Pandas library. This comprehensive guide covers reading, writing, and manipulating Excel data with Pandas, empowering you to perform data analysis and reporting tasks efficiently.
In the realm of Python GUI development, Tkinter stands out as one of the most popular and versatile libraries. Its simplicity and ease of use make it an ideal choice for building graphical user interfaces for various applications.
Learn how to build a scalable microservices architecture using Python and Flask. This comprehensive guide covers setting up Flask for microservices, defining API endpoints, implementing communication between services, containerizing with Docker, deployment strategies, and more.
Learn how to leverage FastAPI, a modern web framework for building APIs with Python, to create high-performance and easy-to-maintain RESTful APIs. FastAPI combines speed, simplicity, and automatic documentation generation, making it an ideal choice for developers looking to rapidly develop and deploy APIs.
Learn how to scrape websites effortlessly using Python's BeautifulSoup library. This beginner-friendly guide walks you through fetching webpages, parsing HTML content, and extracting valuable data with ease.