Development Tutorial

How to Read an RTSP Stream in Python using OpenCV

4 min read

If you are building an AI model for object detection, facial recognition, or license plate reading, you will eventually need to process live video from an IP camera. The standard protocol for this is RTSP (Real-Time Streaming Protocol).

In this tutorial, we will write a simple Python script using the powerful OpenCV library to connect to an RTSP stream, decode the frames, and display them on your screen.

Prerequisites

First, ensure you have Python installed on your system. You will need to install the OpenCV library. Open your terminal and run:

pip install opencv-python

The Python Code

Reading a stream with OpenCV is surprisingly simple. We use the cv2.VideoCapture class, passing our RTSP URL as the argument instead of a file path.

Create a file named read_stream.py and paste the following code:

import cv2

# Replace this with your actual RTSP URL
RTSP_URL = 'rtsp://username:password@192.168.1.100:554/stream1'

# Open the video stream
cap = cv2.VideoCapture(RTSP_URL)

if not cap.isOpened():
    print("Error: Could not open video stream.")
    exit()

print("Successfully connected to the stream. Press 'q' to quit.")

while True:
    # Read a frame from the stream
    ret, frame = cap.read()
    
    if not ret:
        print("Error: Could not read frame. The stream might have ended.")
        break
        
    # Display the frame in a window named 'RTSP Stream'
    cv2.imshow('RTSP Stream', frame)
    
    # Wait for 1 millisecond, and check if the 'q' key was pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Clean up resources
cap.release()
cv2.destroyAllWindows()

How to Test Your Code Without a Camera

Here is the problem most developers face: What do you put in the RTSP_URL variable if you don't have a physical IP camera sitting on your desk?

Testing your code against random public RTSP URLs found on the internet is unreliable (they constantly go offline or have terrible latency).

Get a Reliable Test Stream in 30 Seconds

Don't buy a physical camera just to test your Python script. Use illucam to instantly generate a secure, reliable RTSP stream from your own MP4 files.

Create a Virtual Camera

Troubleshooting Common Issues