Build Your Own Face Recognition Tool With Python
Last Updated :
14 Jan, 2025
From unlocking smartphone to tagging friends on social media face recognition is everywhere. But have you ever wondered how it works? Well, you don’t need to be a computer science expert to create your own face recognition tool. With Python and some basic libraries, you can build one from scratch.
This guide walks through building a face recognition tool, covering the essential steps with practical examples.
Setting Up the Environment
Before diving into the code, let’s set up the environment.
- Prerequisites: Make sure you have Python (3.x version) installed on your machine. You can download it from python.org.
- Libraries Required:
- OpenCV: For image and video processing.
- NumPy: For numerical operations.
pip install opencv-python
pip install numpy
Haar Cascade File: Download the haarcascade_frontalface_default.xml
file, which is a pre-trained model for face detection. You can get it from Haar Cascade File. It is specifically designed to detect objects like faces by applying machine learning algorithms trained on positive and negative images. The Haar Cascade is used to detect faces in images or video frames. Let's build a face recognition tool step-by-step process:
Step 1 : Importing the necessary libraries
Python
import cv2
import numpy as np
Step 2: Setting Up the Video Capture
Use OpenCV’s VideoCapture
function
to access webcam:
Python
video = cv2.VideoCapture(0)
The parameter 0
represents the default camera. If you have multiple cameras, change it to 1
or 2
accordingly to the settings of the camera.
Step 3: Loading the Haar Cascade
Python
facedetect = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml')
here, this haarcascade_frontalface_default.xml file is stored inside the data folder
Step 4: Initializing Variables
Python
With initializing the variables , we will create a list to store face data and a counter to manage frame processing
Step 5: Capturing and Processing Frames
The code is a simple face detection system using OpenCV, which includes grayscale conversion, face detection, data storage, and visual display of the results. It efficiently processes each frame, detecting faces, resizing and storing them, and displaying the results on the screen in real time.
This code takes a live video feed, looks for faces in each frame, and saves some of them. It captures each frame, turns it black and white to make face detection easier, and then finds faces using a face detection tool.
When a face is found, it cuts out that part of the frame, shrinks it to 50x50 pixels, and saves it in a list if the list has fewer than 100 images and the frame count is a multiple of 10. We do this to manage the data efficiently and avoid saving too many similar images, which can happen because the video feed captures frames continuously at a high rate.
The video feed is shown with red rectangle around faces and a number on the screen showing how many faces have been saved. You can stop the program by pressing 'q'
Python
while True:
ret, frame = video.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = facedetect.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
crop_img = frame[y:y+h, x:x+w, :]
resized_img = cv2.resize(crop_img, (50, 50))
if len(faces_data) <= 100 and i % 10 == 0:
faces_data.append(resized_img)
i += 1
cv2.putText(frame, str(len(faces_data)), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (50, 50, 255), 1)
cv2.rectangle(frame, (x, y), (x+w, y+h), (50, 50, 255), 1)
cv2.imshow("Frame", frame)
k = cv2.waitKey(1)
if k == ord('q'):
break
This code efficiently detects faces in a video stream, saves a limited number of resized face images, and visually highlights the detected faces in real time
Step 6: Releasing the Camera
Python
video.release()
cv2.destroyAllWindows()
When you’re done, release the camera and close the OpenCV window.
Complete code for the Face recognition Tool:
Python
import cv2
import numpy as np
video = cv2.VideoCapture(0)
facedetect = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml')
faces_data = []
i = 0
while True:
ret, frame = video.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = facedetect.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
crop_img = frame[y:y+h, x:x+w, :]
resized_img = cv2.resize(crop_img, (50, 50))
if len(faces_data) <= 100 and i % 10 == 0:
faces_data.append(resized_img)
i = i + 1
cv2.putText(frame, str(len(faces_data)), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (50, 50, 255), 1)
cv2.rectangle(frame, (x, y), (x+w, y+h), (50, 50, 255), 1)
cv2.imshow("Frame", frame)
k = cv2.waitKey(1)
if k == ord('q'):
break
video.release()
cv2.destroyAllWindows()
Output:
Face Recognition with OpenCVConclusion:
This code acts like a smart camera that processes a video to identify faces. When it detects faces, it draws rectangles around them to highlight their locations. Additionally, the faces are saved as smaller, cropped images, which can be used later for tasks like face recognition.
Covering each detected face with a red rectangle ensures the code can efficiently focus on the face areas for recognition and avoids processing unnecessary details from the background.
Similar Reads
Build Your Own Voice-Activated Calculator Using Python
In this article, you'll be delving into the development of a voice command calculator using Python, taking advantage of libraries like Speech-Recognition and PyAudio that will allow users with swift means of performing arithmetic operations. Developing such a program will require you to go through s
6 min read
Reading Images With Python - Tkinter
There are numerous tools for designing GUI (Graphical User Interface) in Python such as tkinter, wxPython, JPython, etc where Tkinter is the standard Python GUI library, it provides a simple and efficient way to create GUI applications in Python. Reading Images With Tkinter In order to do various op
2 min read
12 Reasons Why You Should Learn Python [2025]
In the fast-paced world of technology, learning a versatile and in-demand programming language like Python can open doors to numerous opportunities. Python has established itself as a powerhouse in various domains, from web development and data analysis to artificial intelligence and automation. As
8 min read
Finding the Size Resolution of Image in Python
Let us see how to find the resolution of an image in Python. We will be solving this problem with two different libraries which are present in Python: PILOpenCV In our examples we will be using the following image: The resolution of the above image is 600x135. Using PIL We will be using a library na
2 min read
How to Build a Simple Auto-Login Bot with Python
In this article, we are going to see how to built a simple auto-login bot using python. In this present scenario, every website uses authentication and we have to log in by entering proper credentials. But sometimes it becomes very hectic to login again and again to a particular website. So, to come
3 min read
Python | Working with the Image Data Type in pillow
In this article, we will look into some attributes of an Image object that will give information about the image and the file it was loaded from. For this, we will need to import image module from pillow. Image we will be working on : size() method - It helps to get the dimensions of an image. IMG =
2 min read
Open and Run Python Files in the Terminal
The Linux terminal offers a powerful environment for working with Python files, providing developers with efficient ways to open, edit, and run Python scripts directly from the command line. Open and Run Python Files in the Linux TerminalIn this article, we'll explore various techniques and commands
2 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and goin
3 min read
Determine The Face Tilt Using OpenCV - Python
In this article, we are going to see how to determine the face tilt using OpenCV in Python. To achieve this we will be using a popular computer vision library opencv-python. In this program with the help of the OpenCV library, we will detect faces in a live stream from a webcam or a video file and s
4 min read
How to Use Python with Xcode?
Python is a versatile and widely-used programming language, and Xcode is Apple's integrated development environment (IDE) designed primarily for developing software for macOS, iOS, watchOS, and tvOS. Although Xcode is mainly used for Swift and Objective-C development, it can also be set up to work w
3 min read