python中flask框架读取rtsp在web界面展示画面
因项目需求,需要从海康摄像头读取rtsp实时视频流并在web界面展示,达到直播的效果,查阅了很多资料,最初采用了其他的方法实现了此项功能,但是对网络要求过高。
详情请阅读:https://blog.csdn.net/weixin_45457983/article/details/109254606
接下来要说的是使用flask框架实现此功能,flask使用代码:
from flask import Flask, render_template, Response
import cv2
class VideoCamera(object):
def __init__(self):
# 通过opencv获取实时视频流
self.video = cv2.VideoCapture("rtsp地址")
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__)
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', port=5000)
web前端界面代码
<html>
<head>
<title></title>
</head>
<body>
<img src="http://localhost:5000/video_feed"/>
</body>
</html>
在此过程中,若前后端分离,有时存在跨域问题,关于flask解决跨域问题,读着可以直接百度进行处理。
若是在服务器上操作,一定注意5000端口是否被占用,是否已经开放。
如果对我的文章感兴趣,欢迎评论探讨。