Scratch_Vision_Game_dup / test_streaming.py
prthm11's picture
Update test_streaming.py
acaee24 verified
raw
history blame
1.19 kB
from flask import Flask, render_template, request, Response
import base64
import cv2
import numpy as np
from datetime import datetime
app = Flask(__name__)
latest_frame = None # Store the latest frame
@app.route('/')
def index():
return render_template('test_streaming_index.html')
@app.route('/upload_frame', methods=['POST'])
def upload_frame():
global latest_frame
data_url = request.json['image']
header, encoded = data_url.split(",", 1)
img_bytes = base64.b64decode(encoded)
nparr = np.frombuffer(img_bytes, np.uint8)
frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
latest_frame = frame
return '', 204
def stream():
global latest_frame
while True:
if latest_frame is not None:
_, buffer = cv2.imencode('.jpg', latest_frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
else:
yield b''
@app.route('/video_feed')
def video_feed():
return Response(stream(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)