flask实时播放cv2读取的视频

app.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class VideoCamera(object):
def __init__(self, url):
self.cap = cv2.VideoCapture(url)

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.route('/cv2_online')
def cv2_online():
return render_template('cv2_online.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("http://127.0.0.1:5000/static/video.mp4")), mimetype='multipart/x-mixed-replace; boundary=frame')

cv2_online.html

1
2
3
4
5
6
7
8
9
<html>
<head>
<title>Video Streaming Demonstration</title>
</head>
<body>
<h1>Video Streaming Demonstration</h1>
<img src="{{ url_for('video_feed') }}">
</body>
</html>