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

10

我希望使用Python和OpenCV处理来自IP摄像头(交通监控)的mms视频流。该视频流无法受到我的控制。该视频流可用mms或mmst方案获取 -

mms://194.90.203.111/cam2

可以在VLC和Windows Media Player上播放。
mmst://194.90.203.111/cam2

仅适用于VLC。

我已经尝试使用FFmpeg和VLC重新流式传输来更改方案为HTTP,但没有成功。

据我所知,mms使用Windows Media Video对流进行编码。在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。


谢谢 @Ryan!链接中有很多好的信息。Python 部分最后 nailed it。 - NoamR
1个回答

11

使用FFmpeg和FFserver解决。请注意,FFserver仅适用于Linux操作系统。 该解决方案使用这里的Python代码,建议来自Ryan

流程如下 -

  • 使用所需配置(在本例中为mjpeg)启动FFserver后台进程。
  • 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 -


ffserver配置文件 -
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需要更精细的调整,但它们运作得相当好,并且只有一点图像卡顿,可以产生与源非常接近的帧。


2
我非常高兴找到了这个。感谢您分享! - sascha
很遗憾,自从ffmpeg版本3.4.9以后,ffserver已经不再可用。因此将无法使用这个解决方案 :/ - Andre GolFe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接