
A Raspberry Pi can become a useful home security camera capable of capturing video, monitoring an entrance, recording activity, and sending images to another device. With a compatible camera module and the right software, you can build a flexible surveillance system without purchasing a dedicated network camera.
In this tutorial, you’ll learn how to connect a camera to a Raspberry Pi, configure the camera software, record video, and create a basic motion-triggered recording system using Python.
This project is suitable for monitoring a doorway, garage, workshop, home lab, or other private area.
What You’ll Build
The finished system will use a Raspberry Pi and a camera module to capture images and video. You’ll also configure a Python script that detects movement between consecutive frames and saves a recording when activity is detected.
The basic setup includes:
- Live camera preview for initial testing
- Video recording from the terminal
- Motion detection using Python and OpenCV
- Automatic recording when movement is detected
- Local storage for captured video
- Options for secure remote access
The implementation below uses Raspberry Pi OS and the modern rpicam camera stack.
1. Hardware Requirements
You’ll need the following components.
| Component | Purpose |
|---|---|
| Raspberry Pi 4 or Raspberry Pi 5 | Runs the camera software |
| Raspberry Pi Camera Module 3 | Captures images and video |
| Compatible camera ribbon cable | Connects the camera to the Pi |
| microSD card | Stores Raspberry Pi OS and recordings |
| Power supply | Powers the Raspberry Pi |
| Case or camera mount | Protects and positions the hardware |
| Network connection | Enables remote administration |
A Raspberry Pi Zero 2 W can also work for a lightweight camera project, although processing performance and available connectivity may limit more demanding configurations.
The Camera Module 3 is a good starting point because it includes autofocus. For nighttime monitoring, consider a compatible NoIR camera and an appropriate infrared illuminator.
Choosing a camera
The standard Camera Module 3 works well for general indoor monitoring. The Wide version is useful when you need to cover a larger area, while a NoIR module is designed for infrared-sensitive projects.
Make sure the camera module and ribbon cable are compatible with your Raspberry Pi model. Raspberry Pi boards do not all use the same camera connector.
2. Install Raspberry Pi OS
Install Raspberry Pi OS using Raspberry Pi Imager. For a dedicated security camera, Raspberry Pi OS Lite is a sensible option because it avoids the overhead of a full desktop environment.
During setup, configure:
- A unique hostname, such as
pi-security-camera - A strong password
- Your Wi-Fi network if Ethernet is not available
- SSH access if you intend to administer the device remotely
Connect the Raspberry Pi to your network and complete the initial boot.
Update the system:
sudo apt update
sudo apt full-upgrade -y
sudo reboot
After restarting, reconnect through a terminal or SSH.
3. Connect the Camera Module
Turn off and disconnect power from the Raspberry Pi before connecting the camera ribbon cable.
Locate the camera connector on the board. Open its locking tab carefully, insert the ribbon cable straight, and close the tab to secure it.
The cable orientation depends on the connector and board. Follow the official camera installation instructions for your specific Raspberry Pi model.
Reconnect the power supply and start the system.
4. Test the Camera
Recent Raspberry Pi OS versions use the rpicam applications to capture images and video.
Check whether the system detects your camera:
rpicam-still --list-cameras
If the camera appears in the output, capture a test image:
rpicam-still --output test.jpg
You can also preview the camera feed:
rpicam-hello -t 10000
This displays a preview for approximately ten seconds when a display or supported preview environment is available.
For a headless installation, the preview window may not be visible through SSH. That does not necessarily indicate a camera problem; use a capture command to verify that the sensor works.
The rpicam applications are part of Raspberry Pi’s modern camera software stack. Older commands such as raspistill belong to the deprecated legacy camera stack and should not be used for a new installation.
Official documentation: https://www.raspberrypi.com/documentation/computers/camera_software.html
5. Record Video
Once the camera is working, you can record video directly from the command line.
For example, record a 60-second clip:
mkdir -p ~/security-camera/recordings
rpicam-vid \
--timeout 60000 \
--output ~/security-camera/recordings/test.h264
The timeout is expressed in milliseconds, so 60000 represents 60 seconds.
This example writes an H.264 video stream. Depending on your Raspberry Pi model, installed encoders, and desired playback format, you may prefer to record directly into a supported container format using the available rpicam-vid options.
Check the installed application’s options with:
rpicam-vid --help
For continuous surveillance, avoid recording indefinitely into a single file. Shorter recordings are easier to manage, and you can delete old clips automatically to prevent the storage device from filling up.
6. Install the Python Camera and Image-Processing Libraries
Next, you’ll create a simple motion detector.
Install Picamera2 and OpenCV:
sudo apt install -y python3-picamera2 python3-opencv
Picamera2 is the modern Python interface for Raspberry Pi cameras. Installing it through apt is generally recommended because it keeps the Python library compatible with the system camera components.
Documentation:
- Picamera2: https://github.com/raspberrypi/picamera2
- Raspberry Pi camera software: https://www.raspberrypi.com/documentation/computers/camera_software.html
7. Create the Motion Detection Script
Create a project directory and a location for recordings:
mkdir -p ~/security-camera/recordings
cd ~/security-camera
Create the script:
nano security_camera.py
Paste the following code:
import cv2
import time
from datetime import datetime
from pathlib import Path
from picamera2 import Picamera2
RECORDING_DIR = Path.home() / "security-camera" / "recordings"
RECORDING_DIR.mkdir(parents=True, exist_ok=True)
FRAME_WIDTH = 640
FRAME_HEIGHT = 480
MOTION_THRESHOLD = 2500
RECORD_SECONDS_AFTER_MOTION = 10
FPS = 15
camera = Picamera2()
config = camera.create_video_configuration(
main={
"size": (FRAME_WIDTH, FRAME_HEIGHT),
"format": "RGB888",
}
)
camera.configure(config)
camera.start()
time.sleep(2)
previous_gray = None
video_writer = None
record_until = 0
print("Security camera started. Press Ctrl+C to stop.")
try:
while True:
frame = camera.capture_array()
# Convert the image to grayscale and reduce noise.
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
motion_detected = False
if previous_gray is not None:
difference = cv2.absdiff(previous_gray, gray)
_, threshold = cv2.threshold(
difference, 25, 255, cv2.THRESH_BINARY
)
threshold = cv2.dilate(threshold, None, iterations=2)
contours, _ = cv2.findContours(
threshold,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE,
)
for contour in contours:
if cv2.contourArea(contour) > MOTION_THRESHOLD:
motion_detected = True
break
previous_gray = gray
if motion_detected:
record_until = time.time() + RECORD_SECONDS_AFTER_MOTION
# Start a new recording when motion is detected.
if motion_detected and video_writer is None:
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = RECORDING_DIR / f"motion_{timestamp}.avi"
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
video_writer = cv2.VideoWriter(
str(filename),
fourcc,
FPS,
(FRAME_WIDTH, FRAME_HEIGHT),
)
if not video_writer.isOpened():
print("Could not open video file for writing.")
video_writer = None
else:
print(f"Motion detected. Recording: {filename}")
if video_writer is not None:
video_writer.write(
cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
)
if time.time() >= record_until:
video_writer.release()
video_writer = None
print("Recording stopped.")
time.sleep(1 / FPS)
except KeyboardInterrupt:
print("Stopping security camera.")
finally:
if video_writer is not None:
video_writer.release()
camera.stop()
Save the file and exit the editor.
How the script works
The script captures frames from the camera and converts each frame to grayscale. It then compares the current frame with the previous one.
When enough pixels change, the script treats the difference as motion. It begins recording and continues for ten seconds after the most recent detected movement.
The recordings are saved in:
~/security-camera/recordings/
This is a basic motion detector, not a sophisticated person detector. Changes in lighting, moving shadows, trees, and other environmental factors can trigger recordings.
Important recording limitations
This example uses OpenCV’s video writer to create AVI files. The actual recording frame rate can vary with CPU load, camera performance, and encoding speed. For higher-resolution surveillance or long-duration recording, consider using rpicam-vid or a dedicated surveillance application instead.
8. Run the Security Camera
Run the script:
python3 ~/security-camera/security_camera.py
Move in front of the camera or wave your hand to trigger motion detection.
When motion is detected, the script should print a message showing the recording filename. Once activity stops, it closes the recording after the configured delay.
Press Ctrl+C to stop the program cleanly.
List the saved recordings:
ls -lh ~/security-camera/recordings/
If the camera detects motion constantly, try increasing MOTION_THRESHOLD. If it misses movement, reduce the threshold. The best value depends on the camera’s field of view, resolution, lighting, and the distance to the subject.
9. View Recordings Remotely
If SSH is enabled, you can connect to the Raspberry Pi from another computer on the same network:
ssh [email protected]
Replace YOUR_USERNAME with your actual Linux username. If local hostname resolution does not work, use the Raspberry Pi’s IP address instead.
To copy a recording to your computer, run this command from the computer receiving the file:
scp [email protected]:~/security-camera/recordings/motion_2026-01-01_12-00-00.avi .
Replace the example filename with an actual recording.
For live viewing, you can build a web interface or use a dedicated surveillance application. Do not expose the camera’s raw stream or an unauthenticated web server directly to the public internet.
For remote access outside your home, a VPN such as WireGuard or Tailscale is generally safer than forwarding camera or SSH ports on your router.
10. Start the Camera Automatically at Boot
You can use a systemd service to launch the motion detection script when the Raspberry Pi starts.
Create a service file:
sudo nano /etc/systemd/system/security-camera.service
Add the following configuration, replacing YOUR_USERNAME with your Linux username:
[Unit]
Description=Raspberry Pi Security Camera
After=network.target
[Service]
Type=simple
User=YOUR_USERNAME
WorkingDirectory=/home/YOUR_USERNAME/security-camera
ExecStart=/usr/bin/python3 /home/YOUR_USERNAME/security-camera/security_camera.py
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
Save the file, then reload systemd and enable the service:
sudo systemctl daemon-reload
sudo systemctl enable --now security-camera.service
Check the service status:
sudo systemctl status security-camera.service
To view recent messages:
sudo journalctl -u security-camera.service -f
If the service fails, check that the username and paths are correct and that the user has permission to access the camera and write recordings.
11. Configure Storage and Automatic Cleanup
Video files can consume storage quickly. A dedicated microSD card or external USB SSD can help, especially when recordings are frequent.
To delete recordings older than 14 days, you can run:
find "$HOME/security-camera/recordings" \
-type f -mtime +14 -delete
Warning: This command permanently deletes matching files. Test it first without -delete to review which files would be removed.
For example:
find "$HOME/security-camera/recordings" \
-type f -mtime +14 -print
You can schedule the cleanup command with cron or a systemd timer. Make sure the retention period matches your storage capacity and surveillance needs.
12. Improve the Security Camera
Once the basic system works, there are several ways to improve it.
Add night vision
A NoIR camera and compatible infrared illuminator can support night-time monitoring. Check the camera’s infrared sensitivity and the illuminator’s wavelength before choosing components.
Add notifications
The script can be extended to send notifications when motion is detected. Possible options include email, a messaging bot, or a local notification service.
Use environment variables or a protected configuration file for API tokens and credentials. Do not hardcode private credentials into a public repository.
Detect people instead of general motion
OpenCV frame comparison detects changes, not specific objects. A more advanced system can use an object-detection model to distinguish people, vehicles, and animals.
The Raspberry Pi AI Camera is another option for supported neural network inference on the camera module. It requires compatible software and a suitable model.
Improve reliability
For a more dependable setup:
- Use a stable power supply.
- Keep the Raspberry Pi and camera protected from moisture and excessive heat.
- Monitor free storage space.
- Configure automatic restarts and check logs.
- Consider a UPS if the camera must survive short power interruptions.
13. Security and Privacy Considerations
A surveillance camera should be secured like any other network-connected device.
- Use strong, unique passwords and keep the operating system updated.
- Disable services you do not need.
- Restrict access to recordings and administrative accounts.
- Avoid exposing SSH or video streams directly to the internet.
- Use a VPN or another secure remote-access method.
- Inform people where required by local privacy laws, and avoid recording areas where people reasonably expect privacy.
If the camera is used to protect your home, remember that a Raspberry Pi project is not automatically equivalent to a professionally supported security system. Test recording, storage, network recovery, and power-loss behavior before relying on it.
View the Raspberry Pi Security Camera in a Web Browser
You can turn your Raspberry Pi into a simple network camera by streaming live video to a web page. Once configured, you can view the camera from another computer, tablet, or smartphone connected to the same local network.
This method works with a Raspberry Pi 3 and compatible cameras supported by Picamera2.
1. Install the required software
Update Raspberry Pi OS and install Picamera2 if it is not already installed:
sudo apt update
sudo apt install -y python3-picamera2
Test that the camera is detected:
rpicam-still --list-cameras
If your camera is not listed, check the camera cable, connector, and compatibility before continuing.
2. Download the streaming server
Raspberry Pi’s Picamera2 project includes an example that streams MJPEG video using the camera’s hardware encoder.
Download it with:
cd ~
wget https://raw.githubusercontent.com/raspberrypi/picamera2/main/examples/mjpeg_server_2.py
The example provides a basic web page and a live video stream. For a Raspberry Pi 3, it is a useful starting point because it avoids repeatedly capturing and encoding individual frames in a separate Python loop.
3. Start the live camera stream
Run the server:
python3 ~/mjpeg_server_2.py
Leave this terminal open while the server is running.
By default, the server listens on port 8000 and uses a 640 × 480 video stream.
4. Find the Raspberry Pi’s IP address
Open another terminal on the Raspberry Pi, or use a separate SSH session, and run:
hostname -I
For example, the output might contain:
192.168.1.147
Your actual IP address will depend on your network.
5. Open the live camera in a browser
On a phone, tablet, or computer connected to the same local network, open:
http://192.168.1.147:8000
Replace 192.168.1.147 with your Raspberry Pi’s actual IP address.
The browser should display a web page containing the live camera feed. You can bookmark the address to access the camera more easily.
Troubleshooting: If the page does not load, confirm that the Python script is still running, that both devices are on the same network, and that your firewall allows connections to port 8000.
6. Adjust the stream for a Raspberry Pi 3
A Raspberry Pi 3 has limited processing power compared with newer models. The example’s 640 × 480 resolution is a reasonable starting point for a basic security camera.
If the stream is slow or unstable:
- Keep the resolution at 640 × 480.
- Use a wired Ethernet connection if practical.
- Close unnecessary applications.
- Test the stream before enabling motion detection and continuous recording at the same time.
Actual performance will depend on the Pi 3 model, camera, network, and other processes running on the device.
7. Make the stream start automatically
Once you have confirmed that the stream works, you can configure a systemd service to start it at boot. This is useful when the Raspberry Pi is installed in a permanent location.
Create the service file:
sudo nano /etc/systemd/system/security-camera-stream.service
Add the following configuration, replacing YOUR_USERNAME with your Linux username:
[Unit]
Description=Raspberry Pi Security Camera Web Stream
After=network.target
[Service]
Type=simple
User=YOUR_USERNAME
WorkingDirectory=/home/YOUR_USERNAME
ExecStart=/usr/bin/python3 /home/YOUR_USERNAME/mjpeg_server_2.py
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
Save the file, then enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable security-camera-stream
sudo systemctl start security-camera-stream
Check its status:
sudo systemctl status security-camera-stream
If the stream does not start, inspect the logs:
sudo journalctl -u security-camera-stream -n 50 --no-pager
8. Secure access to the camera
This example is intended for a trusted local network. It does not provide user authentication or HTTPS by itself.
For a security camera:
- Do not forward port 8000 directly from your router to the internet.
- Use a VPN, such as WireGuard or Tailscale, when you need remote access.
- Restrict access to trusted devices and networks.
- Remember that anyone who can reach the server may be able to view the feed.
For a more advanced installation, add authenticated access through a properly configured reverse proxy or use a streaming solution designed for secure remote viewing.
You now have a basic Raspberry Pi security camera that can display a live feed in a web browser, alongside the motion-detection and recording functionality described in this guide.
Troubleshooting
The camera is not detected
Check the ribbon cable, connector orientation, camera compatibility, and operating system. Run:
rpicam-still --list-cameras
If no camera appears, consult the official camera troubleshooting documentation.
Python reports that Picamera2 cannot be imported
Install the system package:
sudo apt install python3-picamera2
Run the script with the system Python interpreter rather than an unrelated virtual environment unless that environment is configured to access the system camera libraries.
No recordings are created
Check that the script has permission to write to the recordings directory:
mkdir -p ~/security-camera/recordings
touch ~/security-camera/recordings/test.txt
Also check the terminal output and system logs for errors.
Motion detection triggers too often
Increase MOTION_THRESHOLD, improve lighting, stabilize the camera mount, or adjust the scene so that moving trees and changing light do not dominate the image.
The Raspberry Pi runs slowly
Reduce the frame resolution, reduce the frame rate, or use a more powerful Raspberry Pi. Continuous video encoding and image processing can place a significant load on smaller boards.
Conclusion
Building a security camera with Raspberry Pi is a practical way to learn camera configuration, Python, motion detection, video recording, and Linux service management.
The basic system in this guide captures video when it detects motion and saves recordings locally. From there, you can add remote access, notifications, infrared lighting, or object detection to suit your project.
Start with a reliable camera connection and short test recordings. Then verify that motion detection, storage cleanup, and automatic startup work correctly before using the system for ongoing monitoring.