首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在flask路由中接收摄像头视频流?

如何在flask路由中接收摄像头视频流?
EN

Stack Overflow用户
提问于 2019-04-30 04:41:43
回答 2查看 4.8K关注 0票数 21

我正在开发一个应用程序,它有一个客户端(html&js)和一个服务器(Flask)客户端将打开网络摄像头(HTML5应用程序接口) ->发送视频流到服务器->服务器将返回其他流与json/文本流

我不想玩池子游戏。

我正在研究一些关于视频流的东西,但我在互联网上找到的每一篇文章和例子,都是使用OpenCV的网络摄像头或本地视频,并获得实时网络摄像头的视频并发送到服务器。

以下是我发现的主要示例

服务器:

代码语言:javascript
复制
    from flask import Flask, render_template, Response
    import cv2

    app = Flask(__name__)

    camera = cv2.VideoCapture(0)  # I can't use a local webcam video or a local source video, I must receive it by http in some api(flask) route

    def gen_frames():  # generate frame by frame from camera
        while True:
            success, frame = camera.read()  # read the camera frame
            if not success:
                break
            else:
                ret, buffer = cv2.imencode('.jpg', frame)
                frame = buffer.tobytes()
                yield (b'--frame\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  # concat frame one by one and show result


    @app.route('/video_feed')
    def video_feed():
        """Video streaming route. Put this in the src attribute of an img tag."""
        return Response(gen_frames(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')


    @app.route('/')
    def index():
        """Video streaming home page."""
        return render_template('index.html')


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

客户端: camera.js

代码语言:javascript
复制
          //--------------------
          // GET USER MEDIA CODE
          //--------------------
              navigator.getUserMedia = ( navigator.getUserMedia ||
                                 navigator.webkitGetUserMedia ||
                                 navigator.mozGetUserMedia ||
                                 navigator.msGetUserMedia);

          var video;
          var webcamStream;

          function startWebcam() {
            if (navigator.getUserMedia) {
               navigator.getUserMedia (

                  // constraints
                  {
                     video: true,
                     audio: false
                  },

                  // successCallback
                  function(localMediaStream) {
                      video = document.querySelector('video');
                     video.src = window.URL.createObjectURL(localMediaStream);
                     webcamStream = localMediaStream;
                  },

                  // errorCallback
                  function(err) {
                     console.log("The following error occured: " + err);
                  }
               );
            } else {
               console.log("getUserMedia not supported");
            }  
          }


          //---------------------
          // TAKE A SNAPSHOT CODE
          //---------------------
          var canvas, ctx;

          function init() {
            // Get the canvas and obtain a context for
            // drawing in it
            canvas = document.getElementById("myCanvas");
            context = canvas.getContext('2d');
          }

          function snapshot() {
             // Draws current image from the video element into the canvas
            context.drawImage(video, 0,0, canvas.width, canvas.height);
            webcamStream.stop();
            var dataURL = canvas.toDataURL('image/jpeg', 1.0);
            document.querySelector('#dl-btn').href = dataURL;

            $.ajax({
              type: "POST",
              contentType: false,
              cache: false,
              processData: false,
              async: false,
              url: "/upload",
              data: { 
                imgBase64: dataURL
              }
            }).done(function(o) {
              console.log('saved'); 
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.
    });

          }

index.html

代码语言:javascript
复制
    <!DOCTYPE html>
    <html>

      <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
      <script src="camera.js"></script> 

      </head>
      <body onload="init();">
        <h1>Take a snapshot of the current video stream</h1>
       Click on the Start WebCam button.
         <p>
        <button onclick="startWebcam();">Start WebCam</button>
        <button type="submit" id="dl-btn" href="#" download="participant.jpeg" onclick="snapshot();">Take Snapshot</button> 
        </p>
        <video onclick="snapshot(this);" width=400 height=400 id="video" controls autoplay></video>
      <p>

            Screenshots : <p>
          <canvas  id="myCanvas" width="400" height="350"></canvas>  
      </body>
    </html>

另一个问题是我不能使用快照进行池化,我需要将视频流发送到服务器以处理那里的帧。

有人知道如何将WebCam视频流发送到flask吗?

tks

EN

回答 2

Stack Overflow用户

发布于 2021-01-20 00:41:09

您可能应该在流生成器周围使用stream_with_context来流式传输响应。您不能返回常规响应,因为有任何东西都会告诉客户端不要关闭连接。

https://flask.palletsprojects.com/en/1.1.x/api/#flask.stream_with_context

票数 1
EN

Stack Overflow用户

发布于 2021-02-23 16:12:31

嘿,这可能会帮助你在flask中进行视频流媒体

代码语言:javascript
复制
#!/usr/bin/env python
from flask import Flask, render_template, Response
from camera import Camera

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')

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

    if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55910557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档