|
| 1 | +from flask import Flask, render_template |
| 2 | +from flask_socketio import SocketIO, emit |
| 3 | +import time |
| 4 | +import io |
| 5 | +import base64 |
| 6 | +from PIL import Image |
| 7 | +import cv2 |
| 8 | +import numpy as np |
| 9 | +import pyshine as ps |
| 10 | +from flask_cors import CORS, cross_origin |
| 11 | +from engineio.payload import Payload |
| 12 | + |
| 13 | +Payload.max_decode_packets = 2048 |
| 14 | +app = Flask(__name__) |
| 15 | +socketio = SocketIO(app, cors_allowed_origins='*') |
| 16 | + |
| 17 | +@app.route('/', methods=['POST', 'GET']) |
| 18 | +def index(): |
| 19 | + return render_template('index.html') |
| 20 | + |
| 21 | +def readb64(base64_string): |
| 22 | + idx = base64_string.find('base64,') |
| 23 | + base64_string = base64_string[idx + 7:] |
| 24 | + |
| 25 | + sbuf = io.BytesIO() |
| 26 | + sbuf.write(base64.b64decode(base64_string, ' /')) |
| 27 | + pimg = Image.open(sbuf) |
| 28 | + |
| 29 | + return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR) |
| 30 | + |
| 31 | +def moving_average(x): |
| 32 | + return np.mean(x) |
| 33 | + |
| 34 | +@socketio.on('catch-frame') |
| 35 | +def catch_frame(data): |
| 36 | + emit('response_back', data) |
| 37 | + |
| 38 | +global fps, prev_recv_time, cnt, fps_array |
| 39 | +fps = 60 |
| 40 | +prev_recv_time = 0 |
| 41 | +cnt = 0 |
| 42 | +fps_array = [0] |
| 43 | + |
| 44 | +@socketio.on('image') |
| 45 | +def image(data_image): |
| 46 | + global fps, cnt, prev_recv_time, fps_array |
| 47 | + recv_time = time.time() |
| 48 | + text = 'FPS: ' + str(fps) |
| 49 | + frame = readb64(data_image) |
| 50 | + |
| 51 | + # insert logic here |
| 52 | + """ |
| 53 | + frame = gundetection... |
| 54 | + """ |
| 55 | + |
| 56 | + frame = ps.putBText(frame, text, text_offset_x=20, text_offset_y=30, vspace=20, hspace=10, font_scale=1.0, background_RGB=(10, 20, 222), text_RGB=(255, 255, 255)) |
| 57 | + imgencode = cv2.imencode('.jpeg', frame, [cv2.IMWRITE_JPEG_QUALITY, 40])[1] |
| 58 | + |
| 59 | + stringData = base64.b64encode(imgencode).decode('utf-8') |
| 60 | + b64_src = 'data:image/jpeg;base64,' |
| 61 | + stringData = b64_src + stringData |
| 62 | + |
| 63 | + emit('response_back', stringData) |
| 64 | + |
| 65 | + fps = 1 / (recv_time - prev_recv_time) |
| 66 | + fps_array.append(fps) |
| 67 | + fps = round(moving_average(np.array(fps_array)), 1) |
| 68 | + prev_recv_time = recv_time |
| 69 | + |
| 70 | + cnt += 1 |
| 71 | + if cnt == 30: |
| 72 | + fps_array = [fps] |
| 73 | + cnt = 0 |
| 74 | + |
| 75 | +if __name__ == '__main__': |
| 76 | + socketio.run(app, port=9990, debug=True) |
0 commit comments