chili3d笔记11 连接yolo python http.server 跨域请求 flask

python 复制代码
from ultralytics import YOLO
from flask import Flask, request, jsonify
from flask_cors import CORS
import base64
from io import BytesIO
from PIL import Image
import json

# 加载模型
model = YOLO('./yolo_detect/best.pt')

app = Flask(__name__)
CORS(app)  # 启用跨域支持

def predict(img_data):
    image_data = base64.b64decode(img_data)
    image = Image.open(BytesIO(image_data))
    results = model.predict(source=image)

    predictions = []
    for result in results:
        boxes = result.boxes
        for box in boxes:
            predictions.append({
                "Confidence": box.conf.item(),
                "Object": model.names[int(box.cls.item())],
                "BoxCoordinate": box.xyxy.cpu().numpy().tolist()
            })
    return predictions

@app.route('/', methods=['POST'])
def handle_post():
    payload = request.get_json()
    img_data = payload.get("image_data")

    if not img_data:
        return jsonify({"error": "Missing image data"}), 400

    try:
        result = predict(img_data)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8737)

TypeScript 复制代码
 const fileInput = document.createElement("input");
        fileInput.type = "file";
        fileInput.accept = "image/*";
        fileInput.style.display = "none"; // 隐藏输入框

        // 处理文件选择事件
        fileInput.addEventListener("change", async (event) => {
            const target = event.target as HTMLInputElement;
            this.resultLabel.textContent = "正在上传并检测图像...";
            if (target.files && target.files.length > 0) {
                const file = target.files[0];
                Logger.info(`Selected file: ${file.name}`);

                try {
                    const reader = new FileReader();
                    reader.onload = async () => {
                        try {
                            const base64Data = reader.result?.toString().split(",")[1];
                            const response = await fetch("http://localhost:8737", {
                                method: "POST",
                                headers: { "Content-Type": "application/json" },
                                body: JSON.stringify({ image_data: base64Data }),
                            });

                            if (!response.ok) throw new Error("Network response was not ok");

                            const data = await response.json();

                            const formattedResult = data
                                .map((item: any, index: number) => {
                                    const objType = item.Object;
                                    const confidence = (item.Confidence * 100).toFixed(2);
                                    const [x1, y1, x2, y2] = item.BoxCoordinate[0];
                                    return `目标 ${index + 1}: ${objType}, 置信度 ${confidence}%, 坐标 [${x1.toFixed(1)}, ${y1.toFixed(1)}, ${x2.toFixed(1)}, ${y2.toFixed(1)}]`;
                                })
                                .join("\n");

                            this.resultLabel.textContent = `检测到 ${data.length} 个物体:\n${formattedResult}`;
                            Logger.info("YOLO 检测结果:", data);
                        } catch (error) {
                            Logger.error("请求失败:", error);
                        }
                    };
                    reader.readAsDataURL(file);
                } catch (err) {
                    Logger.error(`处理文件时出错: ${err}`);
                }
            }
        });

2025-05-05 20-32-07 网页端打开图片进行yolo识别,立方体圆柱体

相关推荐
阿米亚波11 小时前
SSH+TCP流程及抓包说明
网络·笔记·网络协议·tcp/ip·计算机网络·wireshark·ssh
爱讲故事的12 小时前
计算机网络第二章:应用层完整复习笔记
笔记·计算机网络
sulikey12 小时前
数据库系统概论 - 定义与查询 期末速成课笔记
数据库·笔记·期末考试·数据查询·期末速成·数据库系统概论·数据定义
hj28625112 小时前
NFS共享存储 完整超详笔记(含原理+流程+命令详解+案例)
笔记
xcLeigh12 小时前
鸿蒙平台 NixNote2 富文本笔记应用适配实战:从 Linux 到 鸿蒙PC 的 Electron 迁移
linux·笔记·harmonyos·富文本·nixnote2·evernote
kdxiaojie12 小时前
Linux 驱动研究 —— SPI (2)
linux·运维·笔记·学习
星恒随风12 小时前
C++ 模板初阶:从泛型编程、函数模板到类模板,一篇打通基础概念
开发语言·c++·笔记·学习
stsdddd12 小时前
YOLO系列目标检测数据集大全【第二十五期】
yolo·目标检测·目标跟踪
LuminousCPP12 小时前
数据结构 - 单链表第二篇:单链表进阶操作
c语言·数据结构·笔记·链表
Zhan86112414 小时前
数据接口的序列号机制与丢包检测:西班牙行情数据IBEX指数实时行情接入笔记
大数据·数据结构·笔记·区块链