main.py
from flask import Flask, render_template, Responseimport cv2class VideoCamera(object): def __init__(self): # 通过opencv获取实时视频流 # url来源见我上一篇博客 self.video = cv2.VideoCapture("http://admin:admin@192.168.10.107:8081/") def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() # 因为opencv读取的图片并非jpeg格式,因此要用motion JPEG模式需要先将图片转码成jpg格式图片 ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes()app = Flask(__name__)@app.route('/') # 主页def index(): # jinja2模板,具体格式保存在index.html文件中 return render_template('index.html')def gen(camera): while True: frame = camera.get_frame() # 使用generator函数输出视频流, 每次请求输出的content类型是image/jpeg 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', debug=True, port=5000)
index.html
<html> <head> <title>Video Streaming Demonstration</title> </head> <body> <h1>Video Streaming Demonstration</h1> <img src="{{ url_for('video_feed') }}"> </body></html>
这篇文章主要介绍了使用Python的Flask框架实现视频的流媒体传输,包括从摄像机获取帧到web浏览器的数字流传输,需要的朋友可以参考下
使用Python的Flask框架实现视频的流媒体传输
联系客服