基于树莓派的智能AI家居安全系统搭建指南
想用树莓派打造一套能识别家人、检测陌生人、还能捕捉包裹递送的智能安防系统?听起来像是专业设备才能干的事,但借助树莓派5和一块AI加速套件,这个项目完全可以在自家桌面上搞定。核心内容包括硬件选型、软件环境配置以及核心代码的实现,下面一步步展开。 这篇文章会带着大家用树莓派和AI能力搭建一个完整的家庭安
想用树莓派打造一套能识别家人、检测陌生人、还能捕捉包裹递送的智能安防系统?听起来像是专业设备才能干的事,但借助树莓派5和一块AI加速套件,这个项目完全可以在自家桌面上搞定。核心内容包括硬件选型、软件环境配置以及核心代码的实现,下面一步步展开。
这篇文章会带着大家用树莓派和AI能力搭建一个完整的家庭安全系统。系统能识别家庭成员、标记陌生人、检测包裹递送,并且通过实时网络通知提醒你。
硬件要求
- Raspberry Pi 5(项目默认使用这一型号)
- Hailo 8L Raspberry Pi AI 套件
- NexiGo 网络摄像头(性能和价格都相当均衡)
- 互联网连接——好在树莓派5自带集成Wi-Fi和以太网口,连网很方便
软件设置
首先给树莓派装好必要的软件。跳过操作系统安装的步骤,因为大多数套件(比如CanaKit的树莓派5套件)已经预装好了系统。直接执行以下命令更新系统并安装依赖:
sudo apt update && sudo apt full-upgrade
sudo apt install hailo-all
git clone https://github.com/hailo-ai/hailo-rpi5-examples.git
cd hailo-rpi5-examples
source setup_env.sh
./compile_postprocess.sh
pip3 install opencv-python-headless numpy supervision pushbullet.py face_recognition
代码
接下来创建主程序文件 smart_security_system.py,内容如下:
import cv2
import numpy as np
import supervision as sv
import face_recognition
import time
from hailo_rpi_common import GStreamerApp, app_callback_class
from pushbullet import Pushbullet
from hailo_models import YoloV5PostProcessing
# Initialize Pushbullet for notifications
pb = Pushbullet("YOUR_API_KEY")
# Load known faces
known_face_encodings = []
known_face_names = []
def load_known_faces(directory):
for filename in os.listdir(directory):
if filename.endswith(".jpg") or filename.endswith(".png"):
image = face_recognition.load_image_file(os.path.join(directory, filename))
encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(encoding)
known_face_names.append(os.path.splitext(filename)[0])
load_known_faces("known_faces")
# Initialize YOLOv5 object detection
yolo_postprocess = YoloV5PostProcessing()
@app_callback_class
class SmartSecurityCallback:
def __init__(self):
self.last_notification_time = 0
self.face_locations = []
self.face_names = []
self.process_this_frame = True
def app_callback(self, buffer, caps):
frame = self.get_numpy_from_buffer(buffer, caps)
# Resize frame for faster face recognition processing
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = small_frame[:, :, ::-1]
if self.process_this_frame:
# Find all faces in the current frame
self.face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, self.face_locations)
self.face_names = []
for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
face_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]
self.face_names.append(name)
self.process_this_frame = not self.process_this_frame
# Detect objects (people and packages)
detections = yolo_postprocess.postprocess(frame)
for detection in detections:
if detection.class_id == 0: # Person
if "Unknown" in self.face_names:
self.send_notification("Stranger detected")
else:
self.send_notification(f"Family member detected: {', '.join(set(self.face_names))}")
elif detection.class_id == 39: # Package (assuming class ID 39 for package in COCO dataset)
self.send_notification("Package delivery detected")
def send_notification(self, message):
current_time = time.time()
if current_time - self.last_notification_time > 60: # Limit to one notification per minute
push = pb.push_note("Smart Security Alert", message)
self.last_notification_time = current_time
def get_numpy_from_buffer(self, buffer, caps):
# Convert GStreamer buffer to numpy array
# Implementation depends on the specific GStreamer setup
pass
def main():
app = GStreamerApp("Smart Security System", SmartSecurityCallback())
app.run()
if __name__ == "__main__":
main()
关于如何将GStreamer的cap缓冲区转换为NumPy数组,这是一个相当常见的问题。下面给出一种实现方案,适用于视频流场景:
import numpy as np
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
def get_numpy_from_buffer(self, buffer, caps):
"""
Convert GStreamer buffer to numpy array
:param buffer: Gst.Buffer
:param caps: Gst.Caps
:return: numpy.ndarray
"""
# Get the Gst.Structure from the caps
structure = caps.get_structure(0)
# Get the width and height of the video frame
width = structure.get_value("width")
height = structure.get_value("height")
# Get the pixel format (assuming it's in caps)
format_info = structure.get_value("format")
# Map the buffer to memory
success, map_info = buffer.map(Gst.MapFlags.READ)
if not success:
raise ValueError("Could not map buffer")
try:
# Get the data from the mapped buffer
data = map_info.data
# Determine the data type and shape based on the pixel format
if format_info == "RGB":
dtype = np.uint8
shape = (height, width, 3)
elif format_info == "RGBA":
dtype = np.uint8
shape = (height, width, 4)
elif format_info == "GRAY8":
dtype = np.uint8
shape = (height, width)
elif format_info == "GRAY16_LE":
dtype = np.uint16
shape = (height, width)
else:
raise ValueError(f"Unsupported format: {format_info}")
# Create numpy array from the buffer data
array = np.ndarray(shape=shape, dtype=dtype, buffer=data)
# Make a copy of the array to ensure it's not tied to the original buffer
return np.array(array)
finally:
# Unmap the buffer
buffer.unmap(map_info)
这段实现做的事情很直观:
- 从GStreamer Caps中提取宽度、高度和像素格式。
- 将缓冲区映射到内存,获取数据。
- 根据像素格式确定NumPy的数据类型和形状。
- 从缓冲区数据创建NumPy数组。
- 返回数组的副本,避免与原始缓冲区绑定。
需要注意的是,这段代码只处理了RGB、RGBA、GRAY8和GRAY16_LE几种常见格式。如果项目需要其他格式(比如YUV),需要自行扩展。另外,确保已安装必要的GStreamer和NumPy依赖:
pip install numpy PyGObject
在Ubuntu或Debian上,还需要安装GStreamer开发库:
sudo apt-get install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
工作原理
- 人脸识别:使用
face_recognition库识别已知人脸。只需将家庭成员的照片放入known_faces目录,系统会自动加载。 - 目标检测:通过Hailo 8L加速的YOLOv5模型检测视频流中的人员和包裹。
- 通知机制:检测到陌生人、家庭成员或包裹递送时,通过Pushbullet发送实时网页通知。
- 性能保障:Hailo 8L AI翻跟斗让实时处理成为可能,响应速度非常快。
系统设置
- 将代码中的
"YOUR_API_KEY"替换为实际的Pushbullet API密钥。 - 在
known_faces目录中放入每位家庭成员的照片,文件名就是该成员的名字(例如john.jpg)。 - 如果使用的YOLOv5模型在Hailo 8L上有特殊配置,可能需要调整
YoloV5PostProcessing的参数。
结语
这个智能家居安全系统充分展示了树莓派与AI加速结合的潜力。Hailo 8L AI套件提供了实时运行复杂模型所需的算力,而NexiGo摄像头保证了高质量的视频输入。通过搭建这套系统,不仅增强了家庭安防能力,也能在AI和计算机视觉领域积累不少实战经验。扩展空间很大——可以添加入侵警报、宠物检测,或者与智能家居设备联动。总之,选对硬件是DIY项目成功的关键,这套组合在性能与成本之间找到了不错的平衡点。

