当前位置: 首页 > news >正文

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

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.boxesfor 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"}), 400try:result = predict(img_data)return jsonify(result)except Exception as e:return jsonify({"error": str(e)}), 500if __name__ == "__main__":app.run(host='0.0.0.0', port=8737)

----------------------------------------------------

 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识别,立方体圆柱体

http://www.dtcms.com/a/172672.html

相关文章:

  • CRS 16 slot 设备硬件架构
  • [学成在线]23-面试题总结
  • window 系统 使用ollama + docker + deepseek R1+ Dify 搭建本地个人助手
  • GZIPOutputStream 类详解
  • GPIO引脚的上拉下拉以及转换速度到底怎么选
  • macbook install chromedriver
  • linux 中inotify与inode的关系是什么?
  • Linux系统编程--基础指令(!!详细讲解+知识拓展)
  • [人机交互]交互设计
  • 物联网mqtt和互联网http协议区别
  • 经典的 Masked + Self-supervised learning 的模型方法
  • “Copy-On-Write” (COW)
  • 基于思考过程评价的心理问题咨询对话记性评估
  • 端口(Port)
  • 【Java ee初阶】多线程(5)
  • 提示词压缩方法总结与开源工具包
  • 1. 设计哲学:让字面量“活”起来,提升表达力和安全性
  • Spring Boot 加载application.properties或application.yml配置文件的位置顺序。
  • Nacos源码—3.Nacos集群高可用分析一
  • Nuxt3还能用吗?
  • Jetpack Compose 响应式布局实战:BoxWithConstraints 完全指南
  • Java IO流核心处理方式详解
  • 【Bootstrap V4系列】学习入门教程之 组件-卡片(Card)
  • 因为gromacs必须安装cuda(系统自带的NVIDIA驱动不行),这里介绍下如何安装cuda
  • SpringMVC——第6章:RESTFul编程风格
  • 51c大模型~合集124
  • 【从零开始学习微服务 | 第一篇】单体项目到微服务拆分实践
  • 深入理解 Bash 中的 $‘...‘ 字符串语法糖
  • DXFViewer进行中 : ->封装OpenGL -> 解析DXF直线
  • Compose 中使用 WebView