OpenCV Python RTSP stream

Viewed 12131

I want to stream the video from IP camera by using RTSP. But I am having a problem. I have installed prerequirements and also, my RTSP link works on VlC player. But when I tried it in the editor and run it, it says Camera could not be found.
Here is my code.

import cv2
import numpy as np
cap = cv2.VideoCapture("rtsp://admin:admin@xxx.xxx.xxx.xxx:xxx/media/video1/video")

while True:
    ret, img = cap.read()
    if ret == True:
    cv2.imshow('video output', img)
    k = cv2.waitKey(10)& 0xff
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
2 Answers

I was able to solve opening an RTSP stream with OpenCV (built with FFMPEG) in Python by setting the following environment variable:

import os
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"

FFMPEG defaults to TCP transport, but some RTSP feeds are UDP, so this sets the correct mode for FFMPEG.

Then use:

cv2.VideoCapture(<stream URI>, cv2.CAP_FFMPEG)

ret, frame = cap.read()

while ret:
    cv2.imshow('frame', frame)
    # do other processing on frame...

    ret, frame = cap.read()
    if (cv2.waitKey(1) & 0xFF == ord('q')):
        break

cap.release()
cv2.destroyAllWindows()

as usual.

Related