CC Blog • Projects • Research & Design Hub

Create an AI-Driven Smart Home Security System

Written by Dhairya A. Parikh

Part 3—Face Recognition and Package Detection

In the pre-Internet Dark Ages, all computing was done locally. Then storage and processing moved to the Cloud. Now, local models are gaining traction again. In this article, Pedro explores the fundamentals of edge computing. He explains the edge computing paradigm, compares it to the cloud-centric paradigm, then presents the advantages and challenges of edge computing, and some solutions in the IoT that could benefit from edge computing adoption.


  • How does face recognition reduce false alerts?
  • What limitations existed in the original system?
  • How is package detection simulated with YOLO?
  • What code updates are required for the new features?
  • How is the web interface improved for detection events?
  • Raspberry Pi 5
  • Hailo AI Kit
  • Python
  • YOLO
  • Flask
  • OpenCV
  • face_recognition
  • dlib
  • NumPy
  • Raspberry Pi | www.raspberrypi.com
  • Python | www.python.org

In Parts 1 and 2 of this article series in the March and April, 2025 issues of Circuit Cellar [1] [2], we started building our AI-powered home security system with a Raspberry Pi 5 and a Hailo AI Kit. We gave it three key functionalities: The ability to detect people in real-time using YOLO (You Only Look Once) models running on the Hailo AI Kit. The model was configured to identify people with high confidence (which is customizable) and reduce false alarms. With an email alert system that notified us whenever an intruder was detected, using a Gmail account with two-step verification and app passwords. We can monitor the camera feed from any device on the same network and view detection results in real time via a local server using the Flask framework in Python to stream the security feed from the Raspberry Pi.

IMPROVEMENTS

Our home security system is already capable of many things, such as detecting intruders, sending timely alerts, and providing real-time video feeds via a web interface (Figure 1). Although the current implementation is functional and adequate in some scenarios, a few gaps still need to be addressed to make the system truly reliable and user friendly.

Figure 1
Web interface we created in the Part 2 of this series. (Yes, that is me!). The stream and detection updates are available across the local network.
Figure 1
Web interface we created in the Part 2 of this series. (Yes, that is me!). The stream and detection updates are available across the local network.

Let’s look at some of these limitations in more detail, to get a better idea of where our system falls short:

Lack of Advanced Person Detection: While the current system can detect people, it cannot detect who the person is. Just imagine a scenario where you install this in your home, and you are alerted every time a family member is detected in the frame. This information won’t be much use, since family members are not a threat to our home’s security. Hence, we need a way for the system to distinguish between known and unknown identities.

Lack of Advanced Features: Although we currently have a feature-rich security system, we can implement a lot of potential improvements to make it even better. For instance, we can add an ability to detect when packages are delivered to our doorstep (no one knocks or hand delivers them), so that we can avoid “porch pirates” and exposure to bad weather in certain scenarios.

To address these limitations, we will now add two advanced features—face recognition and package detection.

Face Recognition: By integrating face recognition, the system will be able to identify family members and friends and reduce unnecessary alerts. This feature can be trained to recognize family members, friends, and frequent visitors, allowing the system to notify only when an unrecognized person is detected.

Package Detection: Adding an object detection model to recognize packages will enable the system to notify users when a delivery is made. While the YOLO model does not support this directly, I’ll create a mock scenario for you, and I will provide you with a great starter guide to implement this feature.

With these improvements, our AI-driven home security system will move one step closer to becoming an intelligent and context-aware security solution that enhances both convenience and safety. Let’s get started by exploring how we can integrate these features into our system.

IMPROVING OUR AI-POWERED HOME SECURITY SYSTEM

The first step was to connect all the hardware together and complete all the steps given in Part 2 of this series [2]. Make sure that you have a running security system before you take the next steps. What this essentially means is that you should be able to see your camera’s output on the web interface, as shown in Figure 1.

Similar to what we did in Part 2, let’s get an idea of how we will be implementing these features into our system before starting with the actual code development.

Face Recognition: By applying this additional filter, we ensure that alerts are triggered only when unknown individuals are detected, reducing false alarms and enhancing system reliability. To integrate face recognition, we will leverage the popular Python package, “face_recognition,” which simplifies the process by allowing us to recognize faces with just a single reference image. (Don’t worry, I’ll cover how to install this.) The flow will be as described below and shown in Figure 2:

  • Load Known Faces: We will load images of family members or frequent visitors and encode them for easy comparison. These face encodings will be stored in memory for quick access.
  • Face Extraction and Comparison: During the detection process, each frame from the camera feed will be analyzed to extract any detected faces. These faces will then be compared against the known face encodings to check for a match.
  • Decision to Send Alert: If the detected face is recognized, the system will suppress the alert, preventing unnecessary notifications. However, if an unrecognized face is detected, an alert will be sent to notify the user.
Figure 2
 Flow diagram explaining how the Face Recognition implementation will work in our security system. It involves an initial set-up phase and frame by frame processing.
Figure 2
Flow diagram explaining how the Face Recognition implementation will work in our security system. It involves an initial set-up phase and frame by frame processing.

Package Detection (Simulation): YOLO models, while excellent at detecting objects, do not have a dedicated label for packages or deliveries. To demonstrate package detection, we will use a creative workaround: We will treat the detection of a bottle as a proxy for identifying a package. While this may not be a perfect real-world analogy, it will allow us to showcase the full flow of adding object detection and sending alerts.

When a bottle is detected in the frame, we will enclose it within a distinct colored bounding box (blue) to differentiate it from person detections. Once a package is “detected,” a separate alert will be sent to the user, notifying them of a potential delivery. We will also enhance our existing Flask interface to display package detection information alongside intruder alerts, thus providing a unified view of all security events.

To implement these new features, we will make modifications to the core detection code (home_security_system_core.py) and the streaming interface (stream_security_video.py). You can find both of these files in the code repository for Part 2 of this article series [3]. Both face recognition and package detection will be seamlessly integrated into the existing system, to ensure that all detections, whether person or package, are handled perfectly.

Now that we have a solid foundation for the changes, we are now ready to dive into the implementation of face recognition and package detection in our AI-powered security system. Let’s get our hands dirty and start updating the code!

CODE WALK-THROUGH

We will be walking through all the existing files from Part 2 of this series that need to be updated to add the two new features to our system. All the code discussed here is available in the Part 3 dedicated GitHub repository [4]. The files that will be updated are:

  • home_security_system_core.py: The main file in which we will implement the face recognition and package detection features.
  • stream_security_video.py: The file that handles the streaming part.
  • index.html: The file that handles the interface we show for streaming our camera.

You can use the Part 2 repository as a starting point and build from there. For this article, we will focus mainly on the home_security_system_core.py, since this is where the main logic changes are needed.

HOME SECURITY SYSTEM CORE CODE

We will start by adding three packages that we will be using for face recognition: NumPy (Python’s scientific computing package); face_recognition [5]; dlib (dependency for the face_recognition package) [6]; and the repository of Hailo examples for the Raspberry Pi 5 [4]. To make things easier for you, I have added a requirements.txt file in this article’s code repository [4]. Listing 1 contains the commands to run on a terminal window to install all the additional dependencies for this project.

cd hailo-rpi5-examples
source setup_env.sh
git clone <repository-link> # available in the references and README file
cd <repository-name>
pip install -r requirements.txt

Listing 1
Commands to run on a terminal window to install all the additional dependencies for this project.

After installing the packages, we are ready to start making code changes. Let’s start by importing the two new libraries that we will be using.

import face_recognition

# Added for face recognition

import numpy as np

# Added for face recognition operations

Next, we add functions to the IntruderDetectionCallback class we created in Part 2, and update a few functions as well. Let’s start by creating two new functions: load_known_faces and recognize_faces (Listing 2).

def load_known_faces(self): “””Load known faces from the specified directory””” logger.info(f”Loading known faces from {self.known_face_dir}”) try: if not os.path.exists(self.known_face_dir): logger.warning(  f”Known faces directory ‘{self.known_face_dir}’ does not exist” ) return for filename in os.listdir(self.known_face_dir): if filename.endswith((“.jpg”, “.jpeg”, “.png”)):  name = os.path.splitext(filename)[0] # Get the name from the filename  image_path = os.path.join(self.known_face_dir, filename)  try:  face_image = face_recognition.load_image_file(image_path)  face_encodings = face_recognition.face_encodings(face_image)  if face_encodings:  self.known_face_encodings.append(face_encodings[0])  self.known_face_names.append(name)  logger.info(f”Loaded face for {name}”)  else:  logger.warning(f”No face found in {filename}”)  except Exception as e:  logger.error(f”Error loading face from {filename}: {str(e)}”) logger.info(f”Loaded {len(self.known_face_names)} known faces”) except Exception as e: logger.error(f”Error during face loading: {str(e)}”)

Listing 2
We add new functions to the IntruderDetectionCallback class we created in Part 2, load_known_faces and recognize_faces.

The first function will be used to load the known face images. For this, you will have to add the images of you and your family members in the “known_faces” folder of your repository (it will be empty by default). Make sure that you rename the image file to the name of the person who is in the image, since that is what the system uses to identify the person.

Now, we will call this function when we start Security system. For this, we will have to make a few changes in the __init__ function (Listing 3).

self.last_package_alert_time = datetime.min # Added for package alerts # Face recognition initialization - NEW self.known_face_dir = “./known_faces” # Directory with known face images self.known_face_encodings = [] self.known_face_names = [] self.load_known_faces()

Listing 3
Additions required in the __init__ function to execute the loading of all the known faces and initializing certain variables we would need.

Note that apart from calling the newly created function, we also define a few new variables that we will be using later in our code. For instance, we use the variable last_package_alert_time to track the last arrived package and the face encoding and names to keep a track of all the known faces in our directory along with their identities.

Next, let’s define the recognize_faces function, which is the main logic behind how faces are recognized in each frame (Listing 4).

def recognize_faces(self, frame):  “””Recognize faces in the frame and return list of known faces found”””  recognized_faces = []  try:   if not self.known_face_encodings:    return recognized_faces       # Resize frame for faster face recognition   small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)   # Convert the image from BGR color (OpenCV) to RGB color (face_recognition)   rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)   # Find all face locations and face encodings in the current frame   face_locations = face_recognition.face_locations(rgb_small_frame)   face_encodings = face_recognition.face_encodings(    rgb_small_frame, face_locations   )   for face_encoding, face_location in zip(face_encodings, face_locations):    # See if the face is a match for the known face(s)    matches = face_recognition.compare_faces(     self.known_face_encodings, face_encoding    )    name = “Unknown”    # Use the known face with the smallest distance to the new face    face_distances = face_recognition.face_distance(     self.known_face_encodings, face_encoding    )    if len(face_distances) > 0:     best_match_index = np.argmin(face_distances)     if matches[best_match_index]:      name = self.known_face_names[best_match_index]      recognized_faces.append(name)  except Exception as e:   logger.error(f”Error during face recognition: {str(e)}”)     return recognized_faces

Listing 4
The core function that implements the face recognition functionality. It compares the detected faces with all the known faces, and if someone matches, it returns the person’s name.

In this function, we do the following for each frame:

  • Transform the frame to make it smaller, and convert it into RGB color mode.
  • Identify where the face is in the frame, and fetch it.
  • Create encodings from the face image, and compare it with all the known encodings.
  • If the comparison yields a positive result, add the identity (name) of that person to the recognized faces list.
  • Return this list.

We have now successfully added face recognition to our system! In addition to the code in Listing 4, I have added a few more things to get cleaner logs, so that you don’t get overwhelmed by them. I am not covering those changes here because they aren’t as important.

Additionally, I have made some changes in the existing email alert functions to send package detection alerts. Since we covered this code in Part 2, I am not discussing it here. You can check the code in the repository [4], since I have added comments wherever necessary for easier understanding.

Our work is not done yet! We still must write the logic to run the face recognition function and package detection logic for every camera frame we get. For that, we must make changes in the app_callback function (the code that runs for each frame).

To enhance the functionality of our AI-driven security system, we have made several significant changes to the app_callback function. These additions allow us to incorporate face recognition for identifying known individuals and package detection using a YOLO proxy label. The final updated function is given in Listing 5.

    # Process each detection
    for detection in detections:
      try:
        confidence = detection.get_confidence()
        label = detection.get_label()

        if confidence > user_data.confidence_threshold:
          bbox = detection.get_bbox()
          track = detection.get_objects_typed(hailo.HAILO_UNIQUE_ID)
          track_id = track[0].get_id() if track else 0

          # Person detection
          if label == “person”:
            # Only add to detection info if not a known face
            if not recognized_faces:
              person_detection_info.append(
                {“id”: track_id, “type”: “person”, “confidence”: confidence}
              )

            # Draw bounding box if frame is available
            if frame is not None:
              x1, y1, x2, y2 = map(
                int,
                [
                  bbox.xmin() * width,
                  bbox.ymin() * height,
                  bbox.xmax() * width,
                  bbox.ymax() * height,
                ],
              )
              # Use green for known persons, red for unknown persons (intruders)
              color = (0, 255, 0) if recognized_faces else (0, 0, 255)
              cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)

              label_text = f”ID: {track_id}”
              if recognized_faces:
                label_text = f”ID: {track_id} - Known: {‘, ‘.join(recognized_faces)}”

              cv2.putText(
                frame,
                label_text,
                (x1, y1 - 10),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.5,
                color,
                2,
              )

          # Package detection (using bottle as proxy)
          elif label == “bottle”:  # Using bottle detection as package proxy
            package_detection_info.append(
              {“id”: track_id, “type”: “package”, “confidence”: confidence}
            )

            # Draw bounding box if frame is available
            if frame is not None:
              x1, y1, x2, y2 = map(
                int,
                [
                  bbox.xmin() * width,
                  bbox.ymin() * height,
                  bbox.xmax() * width,
                  bbox.ymax() * height,
                ],
              )
              # Use blue for packages
              cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
              cv2.putText(
                frame,
                f”Package {track_id}”,
                (x1, y1 - 10),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.5,
                (255, 0, 0),
                2,
              )
      except Exception as e:
        logger.error(f”Error processing detection: {str(e)}”)
      
    # Process each detection
    for detection in detections:
      try:
        confidence = detection.get_confidence()
        label = detection.get_label()

        if confidence > user_data.confidence_threshold:
          bbox = detection.get_bbox()
          track = detection.get_objects_typed(hailo.HAILO_UNIQUE_ID)
          track_id = track[0].get_id() if track else 0

          # Person detection
          if label == “person”:
            # Only add to detection info if not a known face
            if not recognized_faces:
              person_detection_info.append(
                {“id”: track_id, “type”: “person”, “confidence”: confidence}
              )

            # Draw bounding box if frame is available
            if frame is not None:
              x1, y1, x2, y2 = map(
                int,
                [
                  bbox.xmin() * width,
                  bbox.ymin() * height,
                  bbox.xmax() * width,
                  bbox.ymax() * height,
                ],
              )
              # Use green for known persons, red for unknown persons (intruders)
              color = (0, 255, 0) if recognized_faces else (0, 0, 255)
              cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)

              label_text = f”ID: {track_id}”
              if recognized_faces:
                label_text = f”ID: {track_id} - Known: {‘, ‘.join(recognized_faces)}”

              cv2.putText(
                frame,
                label_text,
                (x1, y1 - 10),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.5,
                color,
                2,
              )

          # Package detection (using bottle as proxy)
          elif label == “bottle”:  # Using bottle detection as package proxy
            package_detection_info.append(
              {“id”: track_id, “type”: “package”, “confidence”: confidence}
            )

            # Draw bounding box if frame is available
            if frame is not None:
              x1, y1, x2, y2 = map(
                int,
                [
                  bbox.xmin() * width,
                  bbox.ymin() * height,
                  bbox.xmax() * width,
                  bbox.ymax() * height,
                ],
              )
              # Use blue for packages
              cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
              cv2.putText(
                frame,
                f”Package {track_id}”,
                (x1, y1 - 10),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.5,
                (255, 0, 0),
                2,
              )
      except Exception as e:
        logger.error(f”Error processing detection: {str(e)}”)
        continue

Listing 5The final updated callback function with face recognition and package detection features implemented. This is the function that runs for each captured frame of our system. 

KEY CODE ADDITIONS TO IMPLEMENT NEW FEATURES

The actions of the key additions to the project’s code that were made to implement the proposed new features are summarized here.

Face Recognition Integration:

  • Recognize Faces in Each Frame: Before processing object detections, the updated code now extracts and processes each frame for face recognition. The function user_data.recognize_faces(frame) compares detected faces with known encodings.
  • Filter Out Recognized Faces: If a recognized face is found, it suppresses unnecessary alerts by preventing the system from treating that detection as an intruder. Only unknown faces trigger intruder alerts.
  • Visual Indicators for Recognized/Unknown Faces: A bounding box with different colors is drawn around detected faces—green for recognized faces and red for unknown intruders. The label also updates dynamically to show the names of recognized individuals.

Package Detection Using YOLO Proxy:

  • Simulated Package Detection: Since YOLO does not have a predefined label for packages, we are using a “bottle” as a proxy to demonstrate package detection. When a bottle is detected, it is treated as a package.
  • Drawing Bounding Boxes with Custom Color: Detected packages (bottles) are enclosed within a blue bounding box to distinguish them from green and red bounding boxes used for known person and intruder detections.
  • Separate Package Alerts: Upon package detection, a separate alert is sent to the user, notifying them of a potential delivery.
THE SYSTEM IN ACTION

That’s it for this file. We have successfully made all the changes that were needed. We are now ready to see our system in action. You can run this updated file and check out the logs by bringing an unknown person or a bottle into the frame to see the new additions in action. Moreover, if you have your own face in the system and you enter the frame, you will see a message saying that a known person was detected. Cool, right? Example logs are shown in Figure 3.

Figure 3
Updated logs showing the system’s capability to detect known people, intruders, and packages (simulated as a bottle for now). Additional logs are printed for more information.
Figure 3
Updated logs showing the system’s capability to detect known people, intruders, and packages (simulated as a bottle for now). Additional logs are printed for more information.

In addition to the listed changes, I have altered a few things for the streaming files (the HTML file and the backend Python file stream_security_video.py) to include the package detection updates on the new interface. These code changes are pretty simple and self-explanatory, so I am not describing them here. You can review the new files in the code repository.

Figure 4
The updated user interface for our home security system. Major additions include a new tab for package updates and system logs on the interface, itself.
Figure 4
The updated user interface for our home security system. Major additions include a new tab for package updates and system logs on the interface, itself.

Once you have made all the changes, the updated interface should show package updates in a new tab. Refer to Figure 4 to get a better look at the refreshed interface. There is also a new email alert for packages. You can see a snapshot of what this alert will look like in Figure 5.

Figure 5
A screenshot of the email that will be sent from our home security system every time a new package is detected. Note that the structure and format of the email is similar to the intruder detection alerts, but customized for packages.
Figure 5
A screenshot of the email that will be sent from our home security system every time a new package is detected. Note that the structure and format of the email is similar to the intruder detection alerts, but customized for packages.
CONCLUSION AND NEXT STEPS

That’s it for this three-part article series! We have successfully built our very own AI-powered security system with a Raspberry Pi, a Hailo AI Kit, and a Raspberry Pi camera or other supported USB camera.

In Part 1, we set up the Raspberry Pi and ran our first AI model. In Part 2, we added person detection, email alerts, and a local web interface to monitor the security feed. And in this final part of the series, we enhanced the system by integrating face recognition to identify known individuals, and simulating package detection to notify users about potential deliveries. The result is a robust and intelligent security system that can effectively monitor your home and keep you informed in real time.

While this marks the end of this series, there are still several ways to take this project even further. You can add real-time mobile notifications using push services, integrate cloud storage to log detection data and video feeds, or even scale the system to handle multiple cameras for greater coverage. Additionally, advanced AI models can be used for behavior analysis to detect suspicious activities and improve overall system accuracy.

— ADVERTISMENT—

—Advertise Here—

If you’re looking for more project ideas, consider building a smart doorbell with face recognition, developing an AI-powered pet monitor to keep an eye on your furry friends, or creating an automated package locker system that secures deliveries and notifies you instantly. The possibilities are endless, and with the power of AI and IoT, you can continue to create innovative and high-impact projects. 

RESOURCES
Raspberry Pi | www.raspberrypi.com
Python | www.python.org

REFERENCES
[1] Dhairya Parikh, “Create an AI-Driven Smart Home Security System. Part 1—Setup and First Steps of the Raspberry Pi AI Kit.” Circuit Cellar #416, March, 2025
[2] Dhairya Parikh, “Create an AI-Driven Smart Home Security System. Part 2—Adding Intruder Detection and Alerts.” Circuit Cellar #417, April, 2025
[3] Parikh article, Part 2 Repository: https://github.com/Dhairya1007/Raspberry-Pi-AI-Home-Security-System-Part-2
[4] Parikh article, Part 3 Repository: https://github.com/Dhairya1007/Raspberry-Pi-AI-Home-Security-System-Part-3
[5] Face_recognition Python package: https://github.com/ageitgey/face_recognition
[6] Dlib Python Package: http://dlib.net
[7] Hailo Raspberry Pi 5 Examples Repository: https://github.com/hailo-ai/hailo-rpi5-examples

Code and Supporting Files

PUBLISHED IN CIRCUIT CELLAR MAGAZINE • JUNE 2025 #419 – Get a PDF of the issue

Keep up-to-date with our FREE Weekly Newsletter!

Don't miss out on upcoming issues of Circuit Cellar.


Note: We’ve made the Dec 2022 issue of Circuit Cellar available as a free sample issue. In it, you’ll find a rich variety of the kinds of articles and information that exemplify a typical issue of the current magazine.

Would you like to write for Circuit Cellar? We are always accepting articles/posts from the technical community. Get in touch with us and let's discuss your ideas.

Sponsor this Article
+ posts

Dhairya Parikh is an Electronics Engineer and an avid project developer. Dhairya makes projects that can bring a positive impact in a person’s life by making it easier. He is currently working as an IoT engineer. His projects are mainly related to IoT and machine learning. Dhairya can be contacted on dhairyaparikh1998@gmail.com

Supporting Companies

Upcoming Events


Copyright © KCK Media Corp.
All Rights Reserved

Copyright © 2026 KCK Media Corp.

Create an AI-Driven Smart Home Security System

by Dhairya A. Parikh time to read: 16 min