Accessing the IP camera RTSP stream from Python using cv2.VideoCapture

IP cameras have video streaming protocols to access the videos and images they capture. RTSP (Real-Time Streaming Protocol), is commonly used by most IP cameras to encode videos and broadcast video stream over a network. In this short tutorial, we will go through how to access the video stream through RTSP using cv2.VideoCapture.

To access a video stream through RTSP, we use the RTSP URL. Each camera vendor have their own RTSP URL format including authentication credentials and IP address and port (the default for RTSP is 554) – this usually is stated in the User Manual or just a Google search away. For Hanawa cameras for example, this format is as stated in the code below.

From here, pass the URL to cv2.VideoCapture and loop through the stream to capture each single frame. Tip: If you are struggling to access the URL, verify the camera connection by pinging the IP address (and/or do a sanity check of the URL format).

Here is the sample code to get you started. Good luck!

Laksiya

camera_url = f'rtsp://{username}:{password}@{camera_ip}:554/profile2/media.smp'

# Open the camera stream
cap = cv2.VideoCapture(camera_url)

while True:
    # Read a frame from the camera
    ret, frame = cap.read()

    if not ret:
        print("Failed to read frame from the camera")
        break

    # Display the frame or do some other magic here
    cv2.imshow('Camera Stream', frame)

    # Check for key press, break loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the camera and close all OpenCV windows
cap.release()
cv2.destroyAllWindows()