Spaces:
Runtime error
Runtime error
File size: 2,096 Bytes
5aac002 | 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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | import argparse
import sys
import base64
import json
import cv2
import numpy as np
import torch
from pathlib import Path
from ultralytics import YOLO
import json
from flask import Flask,request_finished
from flask import Flask, request, jsonify
import threading
import time
from flask import Flask
from flask_cors import CORS
from queue import Queue
from flask_socketio import SocketIO, emit
import pickle
app = Flask(__name__)
CORS(app)
socketio = SocketIO(app)
algorithm_running = False
data = {
"code": 0,
"msg": "unknown error",
}
@socketio.on('connect')
def handle_connect():
print('Client connected')
def algorithm_thread(source_rtsp):
global algorithm_running
global data
vid_cap = cv2.VideoCapture(source_rtsp)
while algorithm_running:
success, image = vid_cap.read()
if success:
res = model(image)
res_plotted = res[0].plot()
# 将帧转换为 base64 编码的字符串
_, buffer = cv2.imencode('.jpg', res_plotted)
frame_bytes = buffer.tobytes()
frame_base64 = base64.b64encode(frame_bytes).decode('utf-8')
# 发送帧数据到客户端
socketio.emit('frame_data', {'image': frame_base64})
vid_cap.release()
@app.route("/analyzerControlAdd",methods=['POST'])
def start_algorithm():
global algorithm_running
try:
params = request.get_json()
except:
params = request.form
source_rtsp = params.get("video_url")
print(f"video_url",source_rtsp)
if not algorithm_running :
algorithm_running = True
print("start algorithm")
threading.Thread(target=algorithm_thread(source_rtsp)).start()
@app.route("/analyzerControlCancel", methods=['POST'])
def stop_algorithm():
global algorithm_running
global data
algorithm_running = False
return json.dumps({"code": 1000,"msg": "算法停止!"}, ensure_ascii=False)
if __name__ == "__main__":
model = YOLO('../weights/yolov8n.pt')
app.run(host="0.0.0.0",port=7555)
|