如何停止烧瓶视频流

如何解决如何停止烧瓶视频流

我使用了长颈瓶视频流媒体,并且我想知道在由于检测到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>

解决方法

如果您在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,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.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才能从他的相机中获取图像,并将其发送到服务器并进行处理。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-