【问题标题】:Video Streaming from IP Camera in Python Using OpenCV cv2.VideoCapture使用 OpenCV cv2.VideoCapture 从 Python 中的 IP 摄像机进行视频流传输
【发布时间】:2019-09-13 15:45:08
【问题描述】:

我正在尝试从 IP 摄像机获取 Python 中的视频流,但出现错误。我正在使用 Pycharm IDE。

import cv2
scheme = '192.168.100.23'


host = scheme
cap = cv2.VideoCapture('http://admin:Ebmacs8485867@'+host+':81/web/admin.html')

while True:
    ret, frame = cap.read()

    # Place options to overlay on the video here.
    # I'll go over that later.

    cv2.imshow('Camera', frame)

    k = cv2.waitKey(0) & 0xFF
    if k == 27:  # esc key ends process
        cap.release()
        break
cv2.destroyAllWindows()
Error:
"E:\Digital Image Processing\python\ReadingAndDisplayingImages\venv\Scripts\python.exe" "E:/Digital Image Processing/python/ReadingAndDisplayingImages/ReadandDisplay.py"
Traceback (most recent call last):
  File "E:/Digital Image Processing/python/ReadingAndDisplayingImages/ReadandDisplay.py", line 14, in <module>
    cv2.imshow('Camera', frame)
cv2.error: OpenCV(4.0.1) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:352: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)
warning: http://admin:Ebmacs8485867@192.168.100.23:81/web/admin.html (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)

【问题讨论】:

  • 您尝试检查框架是否为空,可能是空的。
  • 您的意思是 cv2.imshow 无法捕获帧?
  • 不是 imshow(),而是 cap.read()。
  • 该链接是一个网页 (html),您需要 rtsp 链接...这取决于相机的型号。您还应该在循环之前检查if cap.isOpened(),在ret, frame = cap.read() 行之后检查if ret
  • 我也尝试过 rtsp,它也不起作用

标签: python opencv computer-vision video-streaming rtsp


【解决方案1】:

由于流链接无效,您很可能会收到该错误。将您的流链接插入 VLC 播放器以确认它正在工作。这是一个使用 OpenCV 和 cv2.VideoCapture.read() 的 IP 摄像机视频流小部件。由于read() 是一个阻塞操作,因此此实现使用线程来获取不同线程中的帧。通过将此操作放在仅专注于获取帧的单独操作中,它可以通过减少 I/O 延迟来提高性能。我使用了自己的 IP 摄像机 RTSP 流链接。将 stream_link 更改为您自己的 IP 摄像头链接。

根据您的 IP 摄像机,您的 RTSP 流链接会有所不同,这是我的一个示例:

rtsp://username:password@192.168.1.49:554/cam/realmonitor?channel=1&subtype=0
rtsp://username:password@192.168.1.45/axis-media/media.amp

代码

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

【讨论】:

  • 这是个好东西。谢谢。想对self.thread.daemon = True 发表评论吗?谢谢。
  • @user1965074 如果你不将daemon 设置为True,当你的主程序死掉时它将是一个僵尸进程。我们设置了守护进程True,这样当我们的父进程死亡时,这也会杀死所有的子进程。见daemon process boyzzzzzz
  • 我创建了一个 get_frame 函数,如果未设置第一帧,则该函数返回 self.frame 或 np.empty,并为我提供了一组要在类外显示或处理的帧。与 VLC 播放器相比,对象在离开相机几秒钟后出现的延迟非常小,我很惊讶。
  • self.frame 是否需要锁定,以便捕获操作和显示操作不冲突?
猜你喜欢
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
相关资源
最近更新 更多