Spaces:
Sleeping
Sleeping
Create test_streaming.py
Browse files- test_streaming.py +41 -0
test_streaming.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, render_template, request, Response
|
2 |
+
import base64
|
3 |
+
import cv2
|
4 |
+
import numpy as np
|
5 |
+
from datetime import datetime
|
6 |
+
|
7 |
+
app = Flask(__name__)
|
8 |
+
latest_frame = None # Store the latest frame
|
9 |
+
|
10 |
+
@app.route('/')
|
11 |
+
def index():
|
12 |
+
return render_template('index.html')
|
13 |
+
|
14 |
+
@app.route('/upload_frame', methods=['POST'])
|
15 |
+
def upload_frame():
|
16 |
+
global latest_frame
|
17 |
+
data_url = request.json['image']
|
18 |
+
header, encoded = data_url.split(",", 1)
|
19 |
+
img_bytes = base64.b64decode(encoded)
|
20 |
+
nparr = np.frombuffer(img_bytes, np.uint8)
|
21 |
+
frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
22 |
+
latest_frame = frame
|
23 |
+
return '', 204
|
24 |
+
|
25 |
+
def stream():
|
26 |
+
global latest_frame
|
27 |
+
while True:
|
28 |
+
if latest_frame is not None:
|
29 |
+
_, buffer = cv2.imencode('.jpg', latest_frame)
|
30 |
+
frame = buffer.tobytes()
|
31 |
+
yield (b'--frame\r\n'
|
32 |
+
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
|
33 |
+
else:
|
34 |
+
yield b''
|
35 |
+
|
36 |
+
@app.route('/video_feed')
|
37 |
+
def video_feed():
|
38 |
+
return Response(stream(), mimetype='multipart/x-mixed-replace; boundary=frame')
|
39 |
+
|
40 |
+
if __name__ == '__main__':
|
41 |
+
app.run(host='0.0.0.0', port=7860)
|