Build Your Own AI Security Camera with WebRTC (Step by Step)
Smart cameras with "AI person detection" usually come with a monthly cloud fee. You can build the same thing at home with an ordinary IP camera, a small computer and free software. You get a live view in your browser with sub-second latency, plus alerts when a person shows up.
What you need
- Any IP camera or CCTV DVR that gives an RTSP stream (most do)
- A computer to run it: an old laptop, a mini PC or a Raspberry Pi 5
- Python 3.10+
How it fits together
Camera (RTSP) ──► MediaMTX ──► WebRTC ──► Browser (live view)
│
└──► Python + YOLO ──► "Person detected" alert
MediaMTX does the video plumbing. A separate Python script reads the same stream and runs object detection. Keeping them separate means the live view stays smooth even when detection is busy.
Step 1: Live view in the browser
Download MediaMTX, then add your camera to mediamtx.yml:
paths:
frontdoor:
source: rtsp://user:pass@192.168.1.20:554/stream1
Run ./mediamtx and open http://localhost:8889/frontdoor. You now have a live, low-latency stream. (New to this? Read how RTSP-to-WebRTC works first.)
Step 2: Add AI person detection
Install the libraries:
pip install ultralytics opencv-python requests
Create detect.py:
import time, cv2, requests
from ultralytics import YOLO
model = YOLO("yolov8n.pt") # small, fast model
cap = cv2.VideoCapture("rtsp://localhost:8554/frontdoor")
last_alert = 0
while True:
ok, frame = cap.read()
if not ok:
time.sleep(1); continue
results = model(frame, classes=[0], conf=0.5, verbose=False) # class 0 = person
if len(results[0].boxes) and time.time() - last_alert > 60:
last_alert = time.time()
cv2.imwrite("alert.jpg", results[0].plot())
print("Person detected!")
# send yourself a message, e.g. a Telegram bot:
# requests.post(f"https://api.telegram.org/bot<TOKEN>/sendPhoto",
# data={"chat_id": "<CHAT_ID>"}, files={"photo": open("alert.jpg","rb")})
Notice the script reads from MediaMTX (localhost:8554), not the camera directly. Many cheap cameras only allow one or two connections, so MediaMTX shares a single connection with everything.
Step 3: Make it practical
- Save CPU: process one frame every second instead of every frame.
- Fewer false alarms: only alert when the person is inside a zone (a doorway, a gate).
- Recording: MediaMTX can record streams to disk with a setting in the same config file.
- Remote access: use a VPN like Tailscale rather than opening ports on your router.
A mini PC or Raspberry Pi 5 with a good power supply runs this quietly all day on very little electricity.
See optionsMy ebook Camera to Browser walks through a complete RTSP-to-WebRTC setup, with working code and troubleshooting.
Get the ebookNeed something like this built? I take freelance projects in streaming, web apps and automation. Get in touch.