如何使用OpenCV(Python)捕获视频流

2024-10-06 11:21:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python用OpenCV处理mms视频流。 流来自一个我无法控制的IP摄像头(流量监视器)。 流可用作mms或mmst方案-

mms://194.90.203.111/cam2

在VLC和Windows Media Player上播放。

mmst://194.90.203.111/cam2

只适用于VLC。 我曾试图通过使用FFmpeg和VLC重新流式传输将方案更改为HTTP,但没有成功。

据我所知,mms正在使用Windows媒体视频对流进行编码。在URI的末尾加上“.mjpeg”不走运。我还没有找到OpenCV接受的流媒体类型。

这是我的密码-

import cv2, platform
#import numpy as np

cam = "mms://194.90.203.111/cam2"
#cam = 0 # Use  local webcam.

cap = cv2.VideoCapture(cam)
if not cap:
    print("!!! Failed VideoCapture: invalid parameter!")

while(True):
    # Capture frame-by-frame
    ret, current_frame = cap.read()
    if type(current_frame) == type(None):
        print("!!! Couldn't read frame!")
        break

    # Display the resulting frame
    cv2.imshow('frame',current_frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# release the capture
cap.release()
cv2.destroyAllWindows()

那个 我错过了什么?OpenCV可以捕获什么类型的视频流? 有没有一个优雅的解决方案,而不改变方案或转码?

谢谢!

Python 2.7.8版,OpenCV的2.4.9版,都是x86。Win7 x64版本


Tags: 类型ifwindows方案currentcv2frameopencv
1条回答
网友
1楼 · 发布于 2024-10-06 11:21:05

使用FFmpeg和FFserver解决。注意FFserver只在Linux上工作。 该解决方案使用来自here的python代码,如Ryan所建议的。

流程如下-

  • 使用所需配置启动FFserver后台进程 (本例中为mjpeg)。
  • FFmpeg输入是mmst流,输出流 到本地主机。
  • 运行python脚本打开本地主机流并 逐帧解码。

运行FFserver

ffserver -d -f /etc/ffserver.conf

在第二个终端上运行FFmpeg

ffmpeg -i mmst://194.90.203.111/cam2 http://localhost:8090/cam2.ffm

Python代码。在这种情况下,代码将打开一个包含视频流的窗口。

import cv2, platform
import numpy as np
import urllib
import os

cam2 = "http://localhost:8090/cam2.mjpeg"

stream=urllib.urlopen(cam2)
bytes=''
while True:
    # to read mjpeg frame -
    bytes+=stream.read(1024)
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')
    if a!=-1 and b!=-1:
        jpg = bytes[a:b+2]
        bytes= bytes[b+2:]
    frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
    # we now have frame stored in frame.

    cv2.imshow('cam2',frame)

    # Press 'q' to quit 
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

ffserver.config-

Port 8090
BindAddress 0.0.0.0
MaxClients 10
MaxBandWidth 50000
CustomLog -
#NoDaemon

<Feed cam2.ffm>
    File /tmp/cam2.ffm
    FileMaxSize 1G
    ACL allow 127.0.0.1
    ACL allow localhost
</Feed>
<Stream cam2.mjpeg>
    Feed cam2.ffm
    Format mpjpeg
    VideoFrameRate 25
    VideoBitRate 10240
    VideoBufferSize 20480
    VideoSize 320x240
    VideoQMin 3
    VideoQMax 31
    NoAudio
    Strict -1
</Stream>
<Stream stat.html>
    Format status
    # Only allow local people to get the status
    ACL allow localhost
    ACL allow 192.168.0.0 192.168.255.255
</Stream>
<Redirect index.html>
    URL http://www.ffmpeg.org/
</Redirect>

请注意,这个ffserver.config需要进行更多的微调,但它们工作得相当好,只需稍微冻结一点帧,就可以生成非常接近源代码的帧。

相关问题 更多 >