【LattePanda Mu 开发套件】AI 图像识别网页服务器
【LattePanda Mu 开发套件】AI 图像识别网页服务器
本文介绍了 LattePanda Mu 开发套件实现了 AI 图像识别的网页服务器部署,包括关键代码、效果演示等流程。
项目介绍
该项目包括 AI 模型准备、Web 网页服务器部署、图像测试等流程。
- 准备工作:包括硬件及系统安装、Python 部署、库环境安装等;
- 流程图:网页服务器的代码编写逻辑,以及执行框架;
- 代码:包括实现网页服务器的关键 HTML 代码;
- 测试效果:包括测试方案、图像识别流程、方案解析等。
准备工作
-
LattePanda Mu Kit 硬件安装完成,包括 HDMI 连接显示器、电源、鼠标键盘、散热器、局域网连接等;
-
操作系统安装和更新,这里使用 Windows 11 Enterprese IoT LTSC x64 系统;
-
下载并安装 Python 软件,并安装必要的库,如 opencv-python、flask、ultralytics 等;
-
下载 AI 视觉识别所需的 YOLO 预训练模型文件,如 yolov8n.pt ,以便后续调用和快速实现;
详见:【LattePanda Mu 开发套件】AI 视觉应用开发——物体识别- Makelog(造物记) .
流程图
代码
新建 ai_web_server.py
文件,添加如下代码
"""
手机上传 + YOLOv8画框 + 网页回显
单文件运行:python app.py
"""
import cv2
from flask import Flask, render_template_string, request, jsonify
from ultralytics import YOLO
from pathlib import Path
import base64
import numpy as np
from io import BytesIO
from PIL import Imageapp = Flask(__name__)
model = YOLO("models/yolov8n.pt") # 加载模型文件UPLOAD = Path("static")
UPLOAD.mkdir(exist_ok=True)# -------------- 主页 --------------------
HTML = '''
<!doctype html>
<title>AI 图像识别网页服务器</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>body{font-family:Arial;text-align:center;margin:20px}img{max-width:100%;box-shadow:0 0 10px #ccc}#resList{text-align:left;display:inline-block;margin-top:10px}
</style><h2>选择图片 → 上传 → 查看结果</h2>
<form id="uploadForm"><input type="file" name="image" accept="image/*" required><button type="submit">上传识别</button>
</form><div id="output" style="display:none;"><h3>识别结果</h3><img id="resultImg" src=""><div id="resList"></div>
</div><script>
document.getElementById('uploadForm').onsubmit = async (e)=>{e.preventDefault();let fd = new FormData(e.target);let resp = await fetch('/detect', {method:'POST', body:fd});let j = await resp.json();if(j.error){ alert(j.error); return; }// 显示图片document.getElementById('resultImg').src = j.image;// 显示文字let txt = j.objects.map(o=>`${o.label} ${(o.conf*100).toFixed(1)}% 框${o.box}`).join('<br>');document.getElementById('resList').innerHTML = txt || '未检测到物体';document.getElementById('output').style.display = 'block';
}
</script>
'''@app.route("/")
def index():return render_template_string(HTML)# -------------- 识别接口 -----------------
@app.route("/detect", methods=["POST"])
def detect():if "image" not in request.files:return jsonify(error="无文件"), 400file = request.files["image"]img = Image.open(file.stream).convert("RGB")img_np = np.array(img)results = model(img_np)# 画框(无框时返回原图)ann_rgb = results[0].plot() # 返回 RGBif ann_rgb is None:ann_rgb = img_npann_bgr = cv2.cvtColor(ann_rgb, cv2.COLOR_RGB2BGR)ok, buf = cv2.imencode('.jpg', ann_bgr)img_b64 = base64.b64encode(buf).decode()# 文字结果objs = [{"label": results[0].names[int(box.cls)],"conf": float(box.conf),"box": [int(x) for x in box.xyxy[0]]}for box in results[0].boxes]return jsonify(objects=objs, image=f"data:image/jpeg;base64,{img_b64}")# -------------- 启动 --------------------
if __name__ == "__main__":app.run(host="0.0.0.0", port=5000, threaded=True)
- 保存代码;
效果
- 打开命令行终端,进入 python 文件所在路径;
- 运行指令
python ai_web_server.py
;
- 浏览器打开终端提示创建的服务器对应的 HTTP 超链接,如
http://172.31.92.160:5000/
,进入其终端界面;
- 选择
Choose File
打开目标图片,点击上传识别
,即可获得识别结果
更多场景距离,如
- 办公桌面
- 户外运动
同时终端输出识别结果信息
动态效果
总结
该项目实现了 AI 图像识别的网页服务器部署,包括关键代码、效果演示等,特点如下
- 可实现手机等智能终端或边缘 AI 嵌入式设备的远程网络访问,
- 将复杂的 AI 图像识别推理和运算置于云端服务器,
- 极大释放了终端设备的算力要求,
- 降低了终端设备的负担,
- 拓宽了产品在便携式等低功耗需求场景的应用范围。
为相关产品的开发设计和快速应用提供了参考。