如何停止烧瓶视频流

时间:2020-08-11 16:23:06

标签: javascript python flask

我使用了长颈瓶视频流媒体,并且我想知道在由于检测到QRcode而停止流传输之后如何执行另一项操作。在stackoverflow上也提出了类似的问题,答案是使用JavaScript侦听器。但是,考虑到向浏览器提供视频流的是HTML img元素,我的问题是应该在哪个事件上设置javascript监听器。 我已经在图片标签上尝试了多个事件(中止,错误,暂停...),但没有结果。

def gen(camera):
while True:
    frame, is_decoded = camera.get_feed() 
    if is_decoded :
        break
    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():
    camera = get_camera() 
    return Response(gen(camera),
        mimetype='multipart/x-mixed-replace; boundary=frame')

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='style.css') }}">
    <title>Camera App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>

  <body id="bod">
    <center>
      <div id="camera">     
        <img id="cam" src="{{ url_for('video_feed') }}" alt="video feed">
      </div> 
      <script>
            document.getElementById("cam").addEventListener("abort", function() {
              alert("Hello World!");
            });
      </script>

    </center>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

如果您在Supported HTML tags:中检查onabortonendedonstalledonsuspend,则只会看到<video><audio>但没有<img>

可能您将不得不使用JavaScript / AJAX定期询问服务器是否检测到QR。


我发现<img>onload一起使用,后者在每个加载的帧之后执行功能。因此,我将其与Date()一起使用以修正加载最后一帧的时间,并使用setInterval()来检查当前时间与最后一帧时间之间的时差以识别流的结束。我假设如果差值大于1s,则它是流的结尾,但这不是理想的方法,因为有时帧之间的延迟可能更长,但仍将其流化。在页面开始时可能会有更长的延迟,并且可能需要稍后再运行代码。

在烧瓶中,我使用self.stop_time在3秒后停止流播放以模拟流结束。

from flask import Flask, render_template_string, Response
import cv2
import time

app = Flask(__name__)

class Camera():
    
    def __init__(self):
        self.video = cv2.VideoCapture(0)
        self.start_time = time.time() 
        self.stop_time = self.start_time + 3
        
    def __del__(self):
        self.video.release()
        
    def get_feed(self):
        stat, frame = self.video.read()
        ret, jpeg = cv2.imencode('.jpg', frame)
        
        is_decoded = (time.time() >= self.stop_time) # stop stream after 3 seconds
        
        return jpeg.tobytes(), is_decoded
    
# ---

def get_camera():
    return Camera()
    
def gen(camera):
    while True:
        frame, is_decoded = camera.get_feed() 
        if is_decoded:
            print('stop stream')
            break
        yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame + b'\r\n'


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

@app.route('/')
def index():
    return render_template_string(
'''<html>
  <body>
      <img id="cam" src="{{ url_for('video_feed') }}">
      <script>
            var last_frame_time = ''; // no time before first frame to skip longer delay at start
            
            document.getElementById("cam").addEventListener("load", function() { // event "load" is generated after every loaded frame
                last_frame_time = new Date(); 
            });
            
            var intervalId = window.setInterval(function(){
                if(last_frame_time != '') { // to 
                    var current_time = new Date();
                    var seconds = (current_time - last_frame_time)/1000;
                    if(seconds >= 1) {
                        alert("Hello World! " + seconds);
                        clearInterval(intervalId);  // stop checking it
                    }
                }
            }, 100);  // 100ms = 0.1s 
      </script>
  </body>
</html>''')

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

编辑:

对我来说,这是一个更好的例子。它不使用events,但使用AJAX向服务器请求is_decoded,这意味着流媒体结束。它还可以从服务器中解码QR

from flask import Flask, render_template_string, Response, jsonify
import cv2
import time

app = Flask(__name__)

class Camera():
    
    def __init__(self):
        self.video = cv2.VideoCapture(0)
        self.start_time = time.time() 
        self.stop_time  = self.start_time + 5
        self.is_decoded = False  # keep it to send it with AJAX
        
    def __del__(self):
        self.video.release()
        
    def get_feed(self):
        stat, frame = self.video.read()
        ret, jpeg = cv2.imencode('.jpg', frame)
        
        self.is_decoded = (time.time() >= self.stop_time) # stop stream after 5 seconds
        
        return jpeg.tobytes(), self.is_decoded
    
# ---

# create it at start so two functions may use it
camera = Camera()

# send the same camera to two functions
def get_camera():
    return camera
    
def gen(camera):
    # start timer only when start streaming
    camera.start_time = time.time()
    camera.stop_time = camera.start_time + 5
    
    while True:
        frame, is_decoded = camera.get_feed() 
        if is_decoded:
            print('stop stream')
            break
        yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame + b'\r\n'

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

@app.route('/is_decoded/')
def is_decoded():
    camera = get_camera() 
    return jsonify({'is_decoded': camera.is_decoded})

@app.route('/')
def index():
    return render_template_string(
'''<html>
  <head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  
  <body>
      <img id="cam" src="{{ url_for('video_feed') }}">
      <script>
            var intervalId = window.setInterval(function(){
                $.getJSON('/is_decoded/', function(data){
                    if(data['is_decoded'] == true) {
                        alert("Hello World! " + data['is_decoded']);
                        clearInterval(intervalId);  // stop checking it
                    };
                })
            }, 500);  // 500ms = 0.5s 
      </script>
  </body>
</html>''')

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

顺便说一句:

据我了解,您想从用户的网络摄像头中检测到图像上的QRcode-但是cv2仅适用于本地摄像头,如果其他人会远程使用页面,则它将不起作用。它需要JavaScript才能从他的相机中获取图像,并将其发送到服务器并进行处理。