您很可能会因无效的流链接而收到该错误。将您的流链接插入 VLC 播放器以确认其正常工作。这是一个使用 OpenCV 的 IP 摄像机视频流小部件cv2.VideoCapture.read()
。此实现使用线程来获取不同线程中的帧,因为read()
是一个阻塞操作。通过将此操作放入仅专注于获取帧的单独操作中,可以通过减少 I/O 延迟来提高性能。我使用自己的 IP 摄像机 RTSP 流链接。改变stream_link
到您自己的 IP 摄像机链接。
根据您的 IP 摄像机,您的 RTSP 流链接会有所不同,这是我的一个示例:
rtsp://username:[email protected]:554/cam/realmonitor?channel=1&subtype=0
rtsp://username:[email protected]/axis-media/media.amp
Code
from threading import Thread
import cv2
class VideoStreamWidget(object):
def __init__(self, src=0):
# Create a VideoCapture object
self.capture = cv2.VideoCapture(src)
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.frame) = self.capture.read()
def show_frame(self):
# Display frames in main program
if self.status:
self.frame = self.maintain_aspect_ratio_resize(self.frame, width=600)
cv2.imshow('IP Camera Video Streaming', self.frame)
# Press Q on keyboard to stop recording
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
cv2.destroyAllWindows()
exit(1)
# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(self, image, width=None, height=None, inter=cv2.INTER_AREA):
# Grab the image size and initialize dimensions
dim = None
(h, w) = image.shape[:2]
# Return original image if no need to resize
if width is None and height is None:
return image
# We are resizing height if width is none
if width is None:
# Calculate the ratio of the height and construct the dimensions
r = height / float(h)
dim = (int(w * r), height)
# We are resizing width if height is none
else:
# Calculate the ratio of the 0idth and construct the dimensions
r = width / float(w)
dim = (width, int(h * r))
# Return the resized image
return cv2.resize(image, dim, interpolation=inter)
if __name__ == '__main__':
stream_link = 'your stream link!'
video_stream_widget = VideoStreamWidget(stream_link)
while True:
try:
video_stream_widget.show_frame()
except AttributeError:
pass
相关相机/IP/RTSP、FPS、视频、线程和多处理帖子
-
Python OpenCV 从相机流式传输 - 多线程、时间戳
-
使用 OpenCV cv2.VideoCapture 在 Python 中从 IP 摄像机进行视频流传输
-
如何使用 OpenCV 捕获多个摄像机流?
-
OpenCV 实时流视频采集速度很慢。如何丢帧或者实时同步?
-
使用 OpenCV VideoWriter 将 RTSP 流存储为视频文件
-
OpenCV 视频保存
-
Python OpenCV 多处理 cv2.VideoCapture mp4