使用 OpenCV cv2.VideoCapture 在 Python 中从 IP 摄像机进行视频流传输

2023-12-12

我正在尝试从 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:[email protected]:81/web/admin.html (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)

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

enter image description here

根据您的 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、视频、线程和多处理帖子

  1. Python OpenCV 从相机流式传输 - 多线程、时间戳

  2. 使用 OpenCV cv2.VideoCapture 在 Python 中从 IP 摄像机进行视频流传输

  3. 如何使用 OpenCV 捕获多个摄像机流?

  4. OpenCV 实时流视频采集速度很慢。如何丢帧或者实时同步?

  5. 使用 OpenCV VideoWriter 将 RTSP 流存储为视频文件

  6. OpenCV 视频保存

  7. Python OpenCV 多处理 cv2.VideoCapture mp4

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 OpenCV cv2.VideoCapture 在 Python 中从 IP 摄像机进行视频流传输 的相关文章

  • MANIFEST.in、package_data 和 data_files 澄清吗?

    我正在尝试创建一个 Python 包 并且目录结构如下 mypkg init py module1 x py y py z txt module2 a py b py 然后我将所有文件添加到MANIFEST in当我检查创建的存档时 它包含
  • Python 子进程(ffmpeg)仅在我按 Ctrl-C 程序时启动?

    我正在尝试使用 Cygwin 和 Python 2 7 并行运行一些 ffmpeg 命令 这大概是我所拥有的 import subprocess processes set commands ffmpeg i input mp4 outpu
  • ca 证书 Mac OS X

    我需要在emacs 上安装offlineimap 和mu4e 问题是配置 当我运行 Offlineimap 时 我得到 OfflineIMAP 6 5 5 Licensed under the GNU GPL v2 v2 or any la
  • Perl 是否有相当于 Python 的 `if __name__ == '__main__'` 的功能?

    有没有一种方法可以确定当前文件是否是 Perl 源中正在执行的文件 在 Python 中 我们使用以下结构来做到这一点 if name main This file is being executed raise NotImplemente
  • numpy:大量线段/点的快速规则间隔平均值

    我沿着一维线有许多 约 100 万个 不规则间隔的点 P 这些标记线段 这样 如果点是 0 x a x b x c x d 则线段从 0 gt x a x a gt x b x b gt x c x c gt x d 等 我还有每个段的 y
  • 如何使用 i18n 切换器将“LANGUAGE_CODE”保存到数据库,以便在 Django 中的不同浏览器中语言不会更改?

    有什么办法可以改变它的值LANGUAGE CODE单击按钮 发送请求 时 settings py 中的变量会动态变化吗 我希望用户设置自己的 默认语言 他们的帐户 现在 用户可以使用下拉列表选择他们的首选语言 并且网站会得到完美的翻译 并且
  • 返回上个月的日期时间对象

    如果 timedelta 在它的构造函数中有一个月份参数就好了 那么最简单的方法是什么 EDIT 正如下面指出的那样 我并没有认真考虑这一点 我真正想要的是上个月的任何一天 因为最终我只会获取年份和月份 因此 给定一个日期时间对象 返回的最
  • 如何将类添加到 LinkML 中的 SchemaDefinition?

    中的图表https linkml io linkml model docs SchemaDefinition https linkml io linkml model docs SchemaDefinition and https link
  • 在 iPython/pandas 中绘制多条线会生成多个图

    我试图了解 matplotlib 的状态机模型 但在尝试在单个图上绘制多条线时遇到错误 据我了解 以下代码应该生成包含两行的单个图 import pandas as pd import pandas io data as web aapl
  • Pandas groupby apply 执行缓慢

    我正在开发一个涉及大量数据的程序 我正在使用 python pandas 模块来查找数据中的错误 这通常工作得非常快 然而 我当前编写的这段代码似乎比应有的速度慢得多 我正在寻找一种方法来加快速度 为了让你们正确测试它 我上传了一段相当大的
  • 如何使用 django-pyodbc (ubuntu 16.04) 配置数据库设置 Django-MSSQL?

    我是 Django 新手 目前正在尝试使用另一个数据库来保存我的模型 即MS SQL 我的数据库部署在docker容器中 903876e64b67 microsoft mssql server linux bin sh c opt mssq
  • 如何分析组合的 python 和 c 代码

    我有一个由多个 python 脚本组成的应用程序 其中一些脚本正在调用 C 代码 该应用程序现在的运行速度比以前慢得多 因此我想对其进行分析以查看问题所在 是否有工具 软件包或只是一种分析此类应用程序的方法 有一个工具可以将 python
  • 根据列索引重命名 Dataframe 列

    是否有内置函数可以按索引重命名 pandas 数据框 我以为我知道列标题的名称 但事实证明第二列中有一些十六进制字符 根据我接收数据的方式 我将来可能会在第 2 列中遇到这个问题 因此我无法将这些特定的十六进制字符硬编码到 datafram
  • Django Rest Framework POST 更新(如果存在或创建)

    我是 DRF 的新手 我阅读了 API 文档 也许这是显而易见的 但我找不到一个方便的方法来做到这一点 我有一个Answer与 a 具有一对一关系的对象Question 在前端 我曾经使用 POST 方法来创建发送到的答案api answe
  • 在 scipy 中创建新的发行版

    我试图根据我拥有的一些数据创建一个分布 然后从该分布中随机抽取 这是我所拥有的 from scipy import stats import numpy def getDistribution data kernel stats gauss
  • 沿轴 0 重复 scipy csr 稀疏矩阵

    我想重复 scipy csr 稀疏矩阵的行 但是当我尝试调用 numpy 的重复方法时 它只是将稀疏矩阵视为对象 并且只会将其作为 ndarray 中的对象重复 我浏览了文档 但找不到任何实用程序来重复 scipy csr 稀疏矩阵的行 我
  • 如何在Tensorflow中保存估计器以供以后使用?

    我按照教程 TF Layers 指南 构建卷积神经网络 以下是代码 https github com tensorflow tensorflow blob r1 1 tensorflow examples tutorials layers
  • 如何更改matplotlib中双头注释的头大小?

    Below figure shows the plot of which arrow head is very small 我尝试了下面的代码 但它不起作用 它说 引发 AttributeError 未知属性 s k 属性错误 未知属性头宽
  • 如何使用 Python 3 正确显示倒计时日期

    我正在尝试获取将显示的倒计时 基本上就像一个世界末日时钟哈哈 有人可以帮忙吗 import os import sys import time import datetime def timer endTime datetime datet
  • Python 中的字符串slugification

    我正在寻找 slugify 字符串的最佳方法 蛞蝓 是什么 https stackoverflow com questions 427102 in django what is a slug 我当前的解决方案基于这个食谱 http code

随机推荐