OpenCV无法从MJPEG流读取视频

时间:2019-03-01 16:57:05

标签: python python-3.x opencv

我正在尝试使用OpenCV2中的VideoCapture打开一个mjpeg流 但是,每当我尝试读取框架时,都会引发以下错误: [mjpeg @ 0x10f4d20] unable to decode APP fields: Invalid data found when processing input

我可以在浏览器中观看流,而不会出现问题。我还尝试了添加?type=.mjpg这样的虚拟参数但没有运气的典型建议。

这是我打开流的方式:

cap = cv2.VideoCapture("http://localhost:8000/camera/mjpeg?type=.mjpg")
while cap.isOpened():
    ret, image = cap.read()
    if not ret:
        break
    cv2.imshow("Result", image)

3 个答案:

答案 0 :(得分:0)

您需要使用urllib来阅读

import cv2
import urllib.request
import numpy as np

stream = urllib.request.urlopen('http://localhost:8000/camera/mjpeg?type=.mjpg')
bytes = b''
while True:
    bytes += stream.read(1024)
    a = bytes.find(b'\xff\xd8') #frame starting 
    b = bytes.find(b'\xff\xd9') #frame ending
    if a != -1 and b != -1:
        jpg = bytes[a:b+2]
        bytes = bytes[b+2:]
        img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR)
        cv2.imshow('image', img)
        if cv2.waitKey(1) == 27:
            cv2.destroyAllWindows()
            break

答案 1 :(得分:0)

我正是在这样做(Python 3.7),并且正在工作。我有一个Raspberry Pi 4发送流。在同一网络上,我的MacBook运行以下代码。

# Open a URL stream
stream = cv2.VideoCapture('http://192.168.50.1:8080/stream.mjpg')
while ( stream.isOpened() ):
    # Read a frame from the stream
    ret, img = stream.read()
    if ret: # ret == True if stream.read() was successful
        cv2.imshow('Video Stream Monitor', img)

所以我不确定你在做什么错。

答案 2 :(得分:0)

如果您使用的是mjpeg流媒体,请使用流

stream = opencv.VideoCapture('http://localhost:8080/?action=stream')

stream = opencv.VideoCapture('http://XX.XX.XX.XX:8080/?action=stream')