[Flask + OpenCV]制作实时视频流播放网页

参考博文: https://blog.miguelgrinberg.com/post/video-streaming-with-flask

在做一个项目想把opencv 发布到服务器用http 访问,就找了点资料。这篇简单明了,自己经过测试可行。其实原创是国外的,里面很多资料不错。

新建以下目录

在这里插入图片描述

1、在app中输入以下代码,需要安装opencv

from flask import Flask, render_template, Response
import cv2
 
class VideoCamera(object):
    def __init__(self):
        self.cap = cv2.VideoCapture("rtmp://***************") 
    
    def __del__(self):
        self.cap.release()
    
    def get_frame(self):
        success, image = self.cap.read()
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()
 
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', port=5000)

2、在templates文件夹中,新建index.html填写以下内容


<html>
  <head>
    <title>Video Streaming Demonstration</title>
  </head>
  <body>
    <h1>Video Streaming Demonstration</h1>
    <img src="{{ url_for('video_feed') }}">
  </body>
</html>

3、演示效果如下

在这里插入图片描述

发布了62 篇原创文章 · 获赞 235 · 访问量 169万+

猜你喜欢

转载自blog.csdn.net/javastart/article/details/103947953