如何使用Opencv和Flask将网络摄像头图像流广播到多个设备?

时间:2018-11-02 04:09:51

标签: python opencv flask video-streaming opencv-python

我有以下代码。尝试将一台设备连接到服务器时,它工作良好。当两个设备连接时,只有一个设备可以工作,而另一个设备会死机并给出以下错误。

目标是将视频流广播到多个设备。另外,是否有办法通过Flask改善FPS传输并减少延迟?

代码

Camera.py

import cv2

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video = cv2.VideoCapture(0)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

Main.py

import os

install_opencv = os.system("pip install flask opencv-python")
print("Install OPENCV-PYTHON: ", install_opencv)


from flask import Flask, render_template, Response
from camera import VideoCamera

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

错误

Traceback (most recent call last):
cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\imgcodecs\src\grfmt_base.cpp:145: error: (-10:Unknown error code -10) Raw image encoder error: Empty JPEG image (DNL not supported) in function 'cv::BaseImageEncoder::throwOnEror'
127.0.0.1 - - [01/Nov/2018 16:16:21] "GET /video_feed HTTP/1.1" 200

1 个答案:

答案 0 :(得分:0)

我也这样做,无法通过和两个设备访问。 github https://github.com/miguelgrinberg/flask-video-streaming上有一个项目,或者您可以在开发人员的网站https://blog.miguelgrinberg.com/post/flask-video-streaming-revisited #commentform

上看到更好的解释。

使用此代码,我可以从多个设备进行访问,但只允许显示摄像机。我正在努力,以便可以查看2个或更多的摄像机,就像是DVR。

相关问题