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)