How to Build a Face Detection System Using a Raspberry Pi and CircuitDigest Cloud

Published  June 10, 2026   0
User Avatar Vedhathiri
Author
Raspberry Pi Face Detection using CircuitDigest Cloud

When we see movies, we often see scenes where a villain uses a gun with a face detection system that automatically targets a person accurately. It may look like a very complex technology that is difficult to build on our own, right? Not anymore.  Building a face detection system using a Raspberry Pi might sound like something out of a Hollywood thriller, but it is genuinely straightforward once you have the right tools. This project is based on that same concept, where we have built a Raspberry Pi face detection system without any complex setup. We only need a Raspberry Pi, a USB camera, and an account in CircuitDigest Cloud. These three are enough to make the system work; there is no need for model training, data labelling, or collecting datasets manually. Everything is handled through the cloud, making the project simple and practical. Sounds crazy, right? Let’s get in and see how to make this possible. You can also check out similar AI projects and Raspberry Pi projects done previously here at Circuit Digest.

What does this project do?
A USB camera connected to a Raspberry Pi continuously captures frames. OpenCV encodes each frame as a JPEG and sends it to the CircuitDigest Cloud Face Detection API via HTTPS. The cloud AI model analyses the image and returns the face count and confidence score, which the Raspberry Pi displays in the terminal, all in real time, with no local ML model required.

How the Raspberry Pi Face Detection System Works

The system starts with the USB camera continuously capturing live traffic images of riders and vehicles. OpenCV is used to access the camera, display the live video feed, and capture images either manually by pressing the SPACE key in keyboard mode or automatically after a fixed time interval in auto mode. The real-time face detection project follows a straightforward cloud-offload architecture.
After capturing, the image is converted into JPEG format using OpenCV for easy transmission. The Requests library then sends the image securely to the CircuitDigest Cloud Face Detection API using an HTTPS POST request along with the API key. The cloud server processes the image using AI-based face detection and checks whether the face is detected or not. The result is then sent back to the system and displayed in the terminal.

Components Required for the Raspberry Pi Face Detection Project

The components below are the ones that are used to build the face detection using Raspberry tutorial.

S.NoComponents                       Purpose
1.Raspberry piIt is the main controller in this setup for processing.
2.USB CameraUsed to capture the image for processing
3.MicroSD CardStores Raspberry Pi OS and project files

Circuit Diagram Raspberry Pi Face Detection Project

The circuit diagram below shows that the Raspberry Pi is connected to the external power supply for sufficient power, and the USB camera is connected to the Raspberry Pi board's USB port. The Raspberry Pi is connected to the laptop remotely. The hardware setup for this Raspberry Pi face detection system tutorial is minimal.

Circuit Diagram of Face Detection using Raspberry Pi

Step-by-Step Procedure for the Setup of a Face Detection System Using Raspberry Pi

Unlike ESP32 or Arduino, the code cannot be flashed directly to the Raspberry Pi using the Arduino IDE. Before running the project, the Raspberry Pi must be properly set up by installing the operating system on a microSD card. This process is done using Raspberry Pi Imager on a laptop or PC. First, the microSD card is inserted into the system, and through Raspberry Pi Imager, the required Raspberry Pi OS and initial configurations such as Wi-Fi, username, password, and SSH settings are selected and installed. After the OS installation is completed, the SD card is removed and inserted into the Raspberry Pi’s memory card slot, and the board is powered ON. Although the first-time setup may seem like a lot of work, it is actually simple once completed. A detailed step-by-step guide for the complete Raspberry Pi setup can be found in the Raspberry Pi Complete Setup tutorial.

Methods to Access Your Raspberry Pi

  • Direct Hardware Connection
    The first method is by connecting external components such as a monitor, keyboard, and mouse directly to the Raspberry Pi. This allows the Raspberry Pi to work like a normal desktop computer and is mainly useful during the initial setup and for direct operation.
  • Using SSH (Secure Shell)
    The second method is through SSH, where the Raspberry Pi can be accessed remotely from another computer using the same network connection. This method provides command-line control without needing a separate monitor, keyboard, or mouse connected to the Raspberry Pi.
  • Using VNC Viewer
    The third method is by using VNC Viewer, which allows remote access to the full graphical desktop of the Raspberry Pi from another computer. This makes it possible to control the Raspberry Pi exactly like working directly on its own screen, but from a remote location. To work on the setup using VNC Viewer, you can refer to this VNC Viewer for Raspberry Pi tutorial for the detailed step-by-step procedure.

Before stepping into the Thonny IDE present in the Raspberry Pi desktop, first you need the code; for that, follow the steps below.
Step 1⇒ Create Your CircuitDigest Cloud Account
First, you need to make an account on the CircuitDigest Cloud. If you already have one, just go to the CircuitDigest Cloud website, scroll down, and there you will notice the Face detection feature is there; click that, and enter.

CircuitDigest Cloud home page showing the Face Detection feature card on the dashboard

Step 2 ⇒ Explore the Try API Section and Set Confidence

There, you will notice the try api section, various options like image, classes, confidence, result, and a board selection section with its relevant codes. First, you can minimise and maximise the confidence level according to your needs because the confidence value sets the minimum probability threshold for Face detection. A higher value results in more accurate detections but may miss some, while a lower value detects more objects but with less certainty.

CircuitDigest Cloud Face Detection Try API section showing confidence slider, image upload field, and JSON result output

Step 3⇒ Test the API Without Hardware

Now, to try without any microcontroller boards, you need to take a picture that has a lot of people facing towards the camera. Upload it to the image section and click Run Test. In a few seconds, you will get the result with Face detection and its count also.

CircuitDigest Cloud Face Detection API test result showing detected faces, face count, and confidence values for an uploaded image

Step 4⇒ Copy the Raspberry Pi Code and Run It

Below the page, you can see the microcontroller selection. Now, we will try this system with the Raspberry Pi. Click the Raspberry Pi, and the page will give you the code. Just copy the code; now go to the Raspberry Pi desktop, click Thonny IDE for programming. Paste the copied code after making all connections correctly. Nothing, just connect the USB camera to the Raspberry Pi and run the code; that's it. Take any dummy picture from the internet that has lots of people, and you can also test it in real time by taking a picture of someone clearly using the keyboard keys, or you can set it automatically by changing MODE = "keyboard" in the code, like,

  • Keyboard Mode
    In this mode, the user captures the image manually by pressing the SPACE key on the keyboard. It is mainly used when working directly with a monitor or through VNC Viewer.
  • Auto Mode
    In this mode, the system automatically captures images after a fixed time interval without any user interaction. It is useful for continuous monitoring applications.
  • SSH Mode
    In this mode, the program runs through terminal access using SSH and captures images automatically without using the OpenCV display window. The results are shown directly in the terminal.
Python code for Raspberry Pi face detection project displayed in Thonny IDE showing API key, OpenCV camera setup, and HTTPS POST request

The image below shows the captured image from the Raspberry Pi. Along with it, you can see the detection results of the image, whether the face is detected or not. Below that, the Serial Monitor displays the detection output, which includes the count and the confidence value for each identified thing.

Raspberry Pi face detection output showing live camera frame with detected faces highlighted and face count printed in the terminal

Code Explanation for Face Detection Using Raspberry Pi

The code is written in Python for real-time Face detection using a USB camera and CircuitDigest Cloud API. OpenCV is used to capture live images and display the camera feed on the screen. The program supports keyboard mode for manual capture and auto mode for automatic image capture. The captured image is converted into JPEG format for easy transmission. Using the Requests library, the image is sent securely to the cloud API through HTTPS. The server processes the image and returns the helmet detection result in the terminal. The complete script for this Raspberry Pi face detection GitHub-ready project is written in Python 3. 

1. Library Imports and API Configuration

import cv2
import requests
import time
import os
import sysSERVER_URL = "https://www.circuitdigest.cloud/api/v1/face-detection/detect"
API_KEY    = "YourApikey"

This section imports the required Python libraries for camera handling, API communication, timing control, and system operations. OpenCV is used for image capture, while the Requests library sends the captured image to the CircuitDigest Cloud API. The server URL and API key are also defined here for face detection processing.

2. Mode Selection and Camera Initialisation

MODE = "keyboard"
AUTO_INTERVAL = 5
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

This part selects the operating mode of the project, either keyboard mode for manual capture or auto mode for automatic detection. The USB camera is initialized using OpenCV, and the image resolution is set for proper detection quality. The auto interval controls the time gap between automatic captures.

3. Camera Connection Check

if not cap.isOpened():
   print("Camera not found! Check USB camera connection.")
   sys.exit()

This section checks whether the USB camera is properly connected and recognized by the Raspberry Pi. If the camera is not detected, the program displays an error message and stops execution immediately. This prevents the system from running without a valid image input.

4. Image Capture, Encoding, and API Call

_, img_encoded = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 90])
img_bytes = img_encoded.tobytes()
response = requests.post(SERVER_URL, headers=headers,
                       files=files, timeout=15)

This part captures the live image from the camera and converts it into JPEG format for easy transmission. The image is then sent securely to the CircuitDigest Cloud Face Detection API using an HTTPS POST request. The cloud server processes the image and performs face detection.

5. Result Parsing and Display

face_count = result.get("face_count", 0)
print(f"Faces detected: {face_count}")

This section reads the response received from the cloud server after processing the image. It extracts the total number of detected faces and displays the result in the terminal. The system also shows whether no face, one person, or multiple persons are detected clearly.

Troubleshooting of Real-Time Face Detection Project

The five most common issues encountered when building this face detection using a Raspberry Pi system, along with their root causes and verified solutions.

Issue 1: Camera not detected
If the USB camera is not detected, the program may display “Camera not found” and stop running. This usually happens because of a loose USB connection or wrong camera selection. Reconnect the camera properly and make sure it is firmly attached. You can also try changing cv2.VideoCapture(0) to cv2.VideoCapture(1) if another camera device is present.
Issue 2: API request timeout
Sometimes the image may not reach the server, and the program shows a timeout error. This usually happens due to a slow internet connection or unstable network access. Check whether the Raspberry Pi is connected to Wi-Fi or Ethernet properly. Increasing the timeout value in the request function can also help solve this issue.
Issue 3: Invalid API key error
If the API key is incorrect, the cloud server will reject the request and face detection will not work. This can happen if the key is copied incorrectly or has extra spaces. Recheck the API key from the CircuitDigest Cloud account and paste it correctly in the code. Make sure there are no missing or extra characters.
Issue 4: Face not detected properly
Sometimes the system may fail to detect faces because of poor lighting, unclear camera angle, or low image quality. Blurry images and improper face positioning can also affect detection accuracy. Place the camera in a well-lit area and ensure the face is clearly visible. Increasing camera resolution can also improve results.
Issue 5: Program crashes during execution
The program may stop suddenly because of missing Python libraries or invalid frame capture. This usually happens when OpenCV or Requests is not installed properly on the Raspberry Pi. Make sure all required libraries are installed before running the project. Restarting the system and checking the camera feed can also help fix the issue.

Advantages and Limitations of the Face Detection System with Raspberry Pi

The following table gives a clear idea about the limitations and the advantages of Face detection using the Raspberry Pi

S.No                       Advantages                      Limitations
1.Real-time face detection using cloud-based AIRequires a stable internet connection for processing 
2.No need for model training or dataset collection Detection accuracy depends on camera quality 
3.Easy to implement using a Raspberry Pi and a USB camera Poor lighting can reduce detection performance 
4.Supports both manual and automatic capture modesCloud API usage may have daily or monthly limits 
5.Useful for security, attendance, and surveillance systems Slight delay may occur due to API response time 

This Raspberry Pi face detection system tutorial demonstrates that production-grade AI vision capabilities are now accessible to every maker and student, not just professional ML engineers. The key advantage of this setup we don't need to take any datasets manually or download them from the internet, don't need to label the objects, or create any model. With the help of the CircuitDigest Cloud, we are just flashing the code and using it like a ready-made model. This saves time, and with this time we can focus more on other hardware modifications for future enhancements. This method will eliminate the use of ML training websites like Edge Impulse and TensorFlow Lite. Not only have we done ESP32-CAM Face Recognition using an Edge Impulse project; spare some time and go through the project for more details.

Practical Applications of a Raspberry Pi Face Detection System

Raspberry Pi face detection systems are very practical and usable in many varying real-world applications:

  • Attendance Tracking - The Raspberry Pi face detection system can help to automate the attendance process by recording each student or worker's face upon entering the building as well as storing a timestamp and number of faces detected into either a database or a CSV file.
  • Automated Visitor Log and Smart Doorbell - An automated doorbell/visitor log can also be created using the Raspberry Pi face detection system in conjunction with a PIR motion detector to automatically take a picture of anyone arriving at your residence or place of employment and notify you via a Telegram bot or an email that there has been a visitor.
  • People Counting in Retail Stores - By placing a Raspberry Pi face detection system at the entry point of a retail establishment, you can count the number of customers entering the store without any manual input.
  • Home Safety and Security - A face detection Raspberry Pi can be set up as a network-attached device in your home and can be accessed by using SSH. When a person walks in front of the camera, the image of that person can be either saved to an NFS share or uploaded to your cloud storage.
  • Educational Demonstration - This project provides students involved in the maker movement or STEM students in India with an opportunity to learn more about how computers communicate with each other using HTTP, how to work with cloud APIs, and computer vision in general.

Raspberry Pi Face Detection GitHub

Explore the complete source code for the Raspberry Pi Face Detection project on GitHub. The repository includes the face detection implementation, setup instructions, and required dependencies. You can use it as a reference to build, customise, and deploy your own face detection system.

Raspberry Pi Face Detection GitHubRaspberry Pi Face Detection Download Zip

Frequently Asked Questions - Raspberry Pi Face Detection

⇥ Is model training required for this project?
No, model training is not required because the face detection is handled by the CircuitDigest Cloud API. This makes the project simple and easy to implement without collecting datasets or training AI models.

⇥ Does this system work without an internet connection?
No, this system requires an internet connection because the captured image is sent to the CircuitDigest Cloud API for face detection processing. Without the internet, the detection will not work.

⇥ Can I use any USB camera for this project?
Yes, most standard USB webcams can be used with the Raspberry Pi for this project. However, using a better-quality camera improves image clarity and detection accuracy.

⇥ What is the use of keyboard mode and auto mode?
Keyboard mode allows the user to manually capture an image by pressing the SPACE key. Auto mode captures images automatically after a fixed time interval, making it useful for continuous monitoring applications.

⇥ How can I improve face detection accuracy?
You can improve accuracy by placing the camera in proper lighting conditions and keeping the face clearly visible in front of the camera. Increasing image resolution also helps in better detection results.

⇥ Can this system detect multiple faces at the same time?
Yes, the system can detect multiple faces in a single image and display the total face count in the terminal. This makes it useful for crowd monitoring and group detection applications.

Explore these innovative ESP32-CAM projects powered by CircuitDigest Cloud AI. Each project demonstrates how cloud-based computer vision can be integrated into low-cost embedded systems to perform real-time object detection, recognition, and classification without requiring heavy on-device machine learning models.

 How to Make a Waste Detection Using ESP32-CAM with CircuitDigest Cloud

How to Make a Waste Detection Using ESP32-CAM with CircuitDigest Cloud

What if a small device could simply look at the waste and decide whether it is in the biodegradable or non-biodegradable category within seconds? That is exactly what this project does. Let's see what it is and how it works. This project solves that problem with a compact, low-cost waste detection system using image processing.

 How to Build a Smart Indian Currency Recognition Using ESP32-CAM

How to Build a Smart Indian Currency Recognition Using ESP32-CAM

We have done a smart Indian currency recognition system using ESP32-CAM. The system captures an image of the Indian currency note, identifies the denomination within seconds using cloud processing, and announces the result through a speaker.

How to Do Helmet Detection with ESP32-CAM Using CircuitDigest Cloud

How to Do Helmet Detection with ESP32-CAM Using CircuitDigest Cloud

Rather than relying on expensive hardware or complex on-device machine learning, this smart helmet detection system takes a cloud-first approach. A compact ESP32-CAM captures the image and sends it securely to the CircuitDigest Cloud, where powerful AI models do the real work, analysing the image and detecting helmet usage within seconds. 

Complete Project Code

import sys
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
import cv2
import requests
import time
import os
os.environ['DISPLAY'] = ':0'
# -- API Settings -------------------------------------------
SERVER_URL = "https://www.circuitdigest.cloud/api/v1/face-detection/detect"
API_KEY    = "YourApikey"
# -- Mode Selection -----------------------------------------
# "auto"     ? captures every X seconds (VNC / SSH)
# "keyboard" ? press SPACE to capture (Direct Monitor)
MODE          = "keyboard"
AUTO_INTERVAL = 5  # seconds between captures
# -- Camera Setup -------------------------------------------
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
if not cap.isOpened():
   print("Camera not found! Check USB camera connection.")
   sys.exit()
print("Camera initialized.")
print(f"Running in [{MODE}] mode")
if MODE == "keyboard":
   print("Press SPACE to capture | Press ESC to quit")
elif MODE == "auto":
   print(f"Auto capturing every {AUTO_INTERVAL} seconds | Press ESC to quit")
# -- Send Image to API --------------------------------------
def count_faces(frame):
   # Warm-up frames
   for _ in range(3):
       cap.read()
   ret, frame = cap.read()
   if not ret:
       print("Capture failed")
       return
   _, img_encoded = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 90])
   img_bytes = img_encoded.tobytes()
   headers = { "X-API-Key": API_KEY }
   files   = { "imageFile": ("snap.jpg", img_bytes, "image/jpeg") }
   try:
       print("\nPhoto captured! Sending to API...")
       response = requests.post(SERVER_URL, headers=headers,
                                files=files, timeout=15)
       if response.status_code == 200:
           result = response.json()
           safe_response = response.text.encode('utf-8', errors='replace').decode('utf-8')
           print("Response:", safe_response)
           # Parse face count
           face_count = result.get("face_count", 0)
           if face_count == 0:
               face_count = result.get("detection_count", 0)
           print(f"Faces detected: {face_count}")
           if face_count == 0:
               print("Status: No faces detected.")
           elif face_count == 1:
               print("Status: 1 person detected.")
           else:
               print(f"Status: {face_count} persons detected.")
       else:
           print(f"HTTP error: {response.status_code}")
   except requests.exceptions.Timeout:
       print("Request timed out!")
   except Exception as e:
       print(f"Error: {str(e).encode('utf-8', errors='replace').decode('utf-8')}")
# -- Main Loop ----------------------------------------------
last_capture_time = 0
while True:
   ret, frame = cap.read()
   if not ret:
       print("Failed to grab frame")
       break
   cv2.imshow("Face Detection - SPACE: capture | ESC: quit", frame)
   key = cv2.waitKey(1) & 0xFF
   if MODE == "keyboard":
       if key == 32:  # SPACE
           print("\nCapturing image...")
           count_faces(frame)
   elif MODE == "auto":
       current_time = time.time()
       if current_time - last_capture_time >= AUTO_INTERVAL:
           last_capture_time = current_time
           print("\nAuto capturing...")
           count_faces(frame)
   if key == 27:  # ESC
       print("Quitting...")
       break
cap.release()
cv2.destroyAllWindows()
Have any question related to this Article?

Add New Comment

Login to Comment Sign in with Google Log in with Facebook Sign in with GitHub