OpenCV Python Rtsp stream
I want to stream video from an IP camera using RTSP. But I have a problem. I have installed the prerequisites. Also, my RTSP link works on VLC player. But when I try to run it in the editor, it says no camera 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()
source to share
Make sure your opencv installation has the ability to open videos. for this attempt
cap=cv2.VideoCapture(r"path/to/video/file")
ret,img=cap.read()
print ret
If ret
- True
then your opencv installation has the codecs required to handle the video, then confirm that the RTSP address is correct.
If ret
there is False
, then reinstall the opencv, using the steps here . I would recommend building opencv from source. But try the prebuilt libraries first.
source to share
I was able to solve to open an RTSP stream with OpenCV (created with FFMPEG) in Python by setting the following environment variable:
import os
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
FFMPEG uses TCP transport by default, but some RTSP channels 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.
source to share