Daydreamer . 2024-04-01 16:01 采纳率: 0%
浏览 57
已结题

Python flask 一个接口使用yeild 返回摄像头视频流和一个字符串类型的数据

def gen(camera):
    while True:
        res = camera.get_frame()
        if res is None:
            continue
        # 使用generator函数输出视频流, 每次请求输出的content类型是image/jpeg
        frame, _, _, person_count = res
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n' + b'Person Count: ' + str(
            person_count).encode() + b'\r\n\r\n')


@app.route('/video_feed')  # 现场画面界面
def video_feed():
    return Response(gen(VideoCamera(_camera=True)),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

请问,这个写法对吗?不对该怎么写,前端这么接收呢?

  • 写回答

1条回答 默认 最新

  • GISer Liu 2024-04-01 16:08
    关注

    该回答引用自GPT-3.5,由博主GISer Liu编写:

    这个写法有一些问题。首先,生成器函数 gen 中应该使用 yield
    返回每一帧的视频流和人数统计信息。其次,生成的响应应该使用正确的 MIME 类型 multipart/x-mixed-replace,以便前端可以正确解析。最后,前端可以使用 <img> 标签来显示视频流,并从响应中提取人数统计信息。
    下面是修改后的代码示例:
    pythonCopy code

    def gen(camera):
    while True:
    res = camera.get_frame()
    if res is None:
    continue
    frame, _, _, person_count = res
    yield (b'--frame\r\n'
    b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n' +
    b'Person Count: ' + str(person_count).encode() + b'\r\n\r\n')
    @app.route('/video_feed')
    def video_feed():
    return Response(gen(VideoCamera(_camera=True)),
    mimetype='multipart/x-mixed-replace; boundary=frame')
    

    前端可以使用如下的 HTML 代码来显示视频流和人数统计信息:
    htmlCopy code

    <!DOCTYPE html>
    <html>
    <head>
    <title>Video Feed</title>
    </head>
    <body>
    <img id="video_feed" src="{{ url_for('video_feed') }}" />
    <p id="person_count"></p>
    <script>
    const img = document.getElementById('video_feed');
    const countText = document.getElementById('person_count');
    img.onload = function() {
    const count = parseInt(this.src.match(/Person Count: (\d+)/)[1]);
    countText.textContent = 'Person Count: ' + count;
    };
    </script>
    </body>
    </html>
    

    请注意,上述代码仅为示例,实际实现中可能需要根据项目需求进行适当调整。

    如果该回答解决了您的问题,请采纳!如果没有,请参考以下方案进行修订

    用户答题指南

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月1日
  • 创建了问题 4月1日