Create a pet monitoring system with Raspberry Pi
The Raspberry Pi is a versatile single-board computer that, combined with the right components, can be turned into a smart monitoring system for animals. This detailed guide takes you step by step through building such a system, with motion detection, animal recognition and notifications.
Project overview
The project creates an advanced animal monitoring solution capable of:
- Detecting motion using the camera.
- Identifying animals using artificial intelligence (AI).
- Sending customized email notifications including images and the type of animal detected.
- Managing configuration settings (animal types, email, alerts) via a interface web.
Equipment required
- Raspberry Pi 4 (or higher model)
- Camera for Raspberry Pi (official camera module or compatible USB webcam)
- microSD card (32 GB minimum) with Raspberry Pi OS
- Keyboard, mouse and screen for initial setup
- Internet connection (Wi-Fi or Ethernet for the web interface)
Step 1: Installation and initial setup of the Raspberry Pi
- Install Raspberry Pi OS on your microSD card using Raspberry Pi Imager.
- Start and configure the Raspberry Pi (network, date, language).
- Update the system :
sudo apt update && sudo apt upgrade -y
Step 2: Preparing the camera and installing the AI libraries
2.1 Enable and test the camera
Enable the camera:
sudo raspi-config
Test the camera:
raspistill -o test.jpg
2.2 Install OpenCV and TensorFlow Lite
Install OpenCV for image detection:
sudo apt install python3-opencv -y
Download and set up the MobileNet SSD model for animal recognition:
mkdir ~/models && cd ~/models
wget https://storage.googleapis.com/download.tensorflow.org/models/tflite/coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip
unzip coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip
Step 3: Motion detection and animal recognition
We will create a Python script to analyze the images and detect animals.
Create a file animal_surveillance.py :
nano animal_surveillance.py
Add the following code to set up motion detection, image capture and animal recognition:
import cv2
import tensorflow as tf
import numpy as np
from datetime import datetime
import os
# Charger le modèle TensorFlow Lite
interpreter = tf.lite.Interpreter(model_path="~/models/detect.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Définir les classes d'animaux détectables
ANIMAL_CLASSES = {16: "Oiseau", 17: "Chat", 18: "Chien"}
DETECTION_THRESHOLD = 0.5
# Initialiser la caméra
camera = cv2.VideoCapture(0)
first_frame = None
# Fonction pour détecter les animaux
def detect_animal(frame):
input_shape = input_details[0]['shape']
frame_resized = cv2.resize(frame, (input_shape[1], input_shape[2]))
input_data = np.expand_dims(frame_resized, axis=0)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
boxes = interpreter.get_tensor(output_details[0]['index'])[0]
classes = interpreter.get_tensor(output_details[1]['index'])[0]
scores = interpreter.get_tensor(output_details[2]['index'])[0]
for i in range(len(scores)):
if scores[i] >= DETECTION_THRESHOLD:
return ANIMAL_CLASSES.get(int(classes[i]), "Inconnu")
return None
# Fonction pour détecter les mouvements
def detect_motion():
global first_frame
ret, frame = camera.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
if first_frame is None:
first_frame = gray
return None
delta_frame = cv2.absdiff(first_frame, gray)
thresh_frame = cv2.threshold(delta_frame, 25, 255, cv2.THRESH_BINARY)[1]
thresh_frame = cv2.dilate(thresh_frame, None, iterations=2)
contours, _ = cv2.findContours(thresh_frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 5000:
continue
animal = detect_animal(frame)
if animal:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
image_path = f"/home/pi/captures/{animal}_{timestamp}.jpg"
cv2.imwrite(image_path, frame)
return animal, image_path
return None, None
if __name__ == "__main__":
os.makedirs("/home/pi/captures", exist_ok=True)
print("Surveillance animale en cours...")
while True:
animal, image_path = detect_motion()
if animal:
print(f"Animal détecté : {animal}")
# Notifications et alertes peuvent être ajoutées ici
The script detects motion, recognizes animalsand saves an image capture for each detection.
Step 4: Flask web interface to configure settings and display captures
For easier management, we will create a web interface to configure alert settings and view captured images.
4.1 Installing Flask
pip3 install flask
4.2 Creating the Flask server
Create a file app.py for the interface:
nano app.py
Add the following Flask code to set up the web interface:
from flask import Flask, render_template, request, redirect, url_for
import os
app = Flask(__name__)
# Stockage des paramètres
config = {
"email": "destination_email@example.com",
"animals": ["Chat", "Chien"]
}
@app.route("/")
def index():
captures = os.listdir("/home/pi/captures/")
captures = [f"/static/captures/{capture}" for capture in captures]
return render_template("index.html", config=config, captures=captures)
@app.route("/settings", methods=["POST"])
def settings():
config["email"] = request.form["email"]
config["animals"] = request.form.getlist("animals")
return redirect(url_for("index"))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
Create the HTML template index.html to manage the configuration and view captures:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Surveillance Animale</title>
</head>
<body>
<h1>Configuration de Surveillance Animale</h1>
<form action="/settings" method="post">
<label for="email">E-mail de Notification :</label>
<input type="email" name="email" value="{{ config.email }}" required><br>
<label>Animaux Suivis :</label><br>
<input type="checkbox" name="animals" value="Chat" {% if "Chat" in config.animals %}checked{% endif %}> Chat<br>
<input type="checkbox" name="animals" value="Chien" {% if "Chien" in config.animals %}checked{% endif %}> Chien<br>
<button type="submit">Enregistrer</button>
</form>
<h2>Captures :</h2>
{% for capture in captures %}
<img src="{{ capture }}" width="300"><br>
{% endfor %}
</body>
</html>
Start the Flask server:
python3 app.py
Access the interface at http://<adresse_ip_du_raspberry_pi>:5000.
Step 5: Setting up email notifications with captures and animal details
5.1 Installing and configuring email sending
To send notifications, we will use smtplib, a standard Python library for sending emails via an SMTP server (for example, Gmail).
Create a configuration file to store your email login details securely.
Create a file config.py
nano config.py
Add the following login details (replacing them with your address and password):
EMAIL_ADDRESS = "votre_email@gmail.com"
EMAIL_PASSWORD = "votre_mot_de_passe"
Save and close the file.
Enable less secure app access in your Google account (if you use Gmail), because smtplib requires authorization to access your account via SMTP.
5.2 Adding the email sending function to the monitoring script
Modifiez animal_surveillance.py to include the email sending function, incorporating the captured image and the detected animal type
Open animal_surveillance.py and add the following function for sending emails:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import config # Importer le fichier config pour récupérer l'email et le mot de passe
def send_email_alert(image_path, detected_animal):
# Créer un e-mail
msg = MIMEMultipart()
msg['From'] = config.EMAIL_ADDRESS
msg['To'] = config.EMAIL_ADDRESS # Envoyer à vous-même ou à l’adresse spécifiée dans config
msg['Subject'] = f"Alerte : {detected_animal} détecté !"
# Ajouter le corps du message
body = f"Un {detected_animal} a été détecté par le système de surveillance animale."
msg.attach(MIMEText(body, 'plain'))
# Ajouter l'image en pièce jointe
with open(image_path, 'rb') as f:
img_data = f.read()
image = MIMEImage(img_data, name=os.path.basename(image_path))
msg.attach(image)
# Envoi de l'e-mail via SMTP
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(config.EMAIL_ADDRESS, config.EMAIL_PASSWORD)
server.sendmail(config.EMAIL_ADDRESS, config.EMAIL_ADDRESS, msg.as_string())
server.quit()
print("E-mail envoyé avec succès.")
except Exception as e:
print(f"Erreur lors de l'envoi de l'e-mail : {e}")
Integrate the email sending function into the detection script:
- Modify the part
if animal:indetect_motion()to send an email with the details of the detected animal.
if animal:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
image_path = f"/home/pi/captures/{animal}_{timestamp}.jpg"
cv2.imwrite(image_path, frame)
print(f"{animal} détecté. Image sauvegardée : {image_path}")
send_email_alert(image_path, animal) # Appel de la fonction d'envoi d'e-mail
Save and close the file animal_surveillance.py.
Test the script by running:
python3 animal_surveillance.py
When the system detects motion and recognizes an animal, it sends an email to the configured address with the image of the detected animal and the type of animal in the email subject.
Conclusion
This guide provides a complete smart animal monitoring system using the Raspberry Pi. Thanks to motion detection, animal recognition, a web configuration interface and notifications e-mail with full details, this project is a powerful and flexible solution for monitoring your animals. You can easily customize alert settings and add new animal types via the web configuration.