You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask网页实现.h5模型与图片上传并调用脚本返回结果方法咨询

完全可行,这是Flask构建AI推理Web应用的典型场景,以下是完整实现方案:

项目结构

先整理清晰的目录结构,方便管理模型、前端文件和上传资源:

your_project/
├── app.py                # Flask主程序
├── templates/
│   └── index.html        # 前端交互页面
├── static/
│   └── css/
│       └── style.css     # 页面样式(可选)
├── uploads/              # 上传图片存放目录(自动生成)
└── models/               # 存放8个.h5模型文件
    ├── model_a.h5
    ├── model_b.h5
    └── ...

Flask后端实现(app.py)

核心逻辑包含模型加载、图片上传校验、推理执行三个部分,代码如下:

from flask import Flask, render_template, request, flash, redirect, url_for
import tensorflow as tf
import os
from PIL import Image
import numpy as np

app = Flask(__name__)
app.secret_key = "random_secret_key_123"  # 用于提示消息的加密
app.config["UPLOAD_FOLDER"] = "uploads/"
app.config["ALLOWED_EXTENSIONS"] = {"png", "jpg", "jpeg"}
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024  # 限制上传图片最大16MB

# 自动创建必要目录
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
MODEL_DIR = "models/"

def allowed_file(filename):
    # 校验上传文件格式
    return "." in filename and filename.rsplit(".", 1)[1].lower() in app.config["ALLOWED_EXTENSIONS"]

def load_selected_model(model_name):
    # 加载选中的.h5模型
    model_path = os.path.join(MODEL_DIR, model_name)
    return tf.keras.models.load_model(model_path)

def run_inference(model, image_path):
    # 图片预处理+推理逻辑,需根据你的模型训练参数调整
    img = Image.open(image_path).resize((224, 224))  # 示例:模型输入尺寸224x224
    img_array = np.array(img) / 255.0  # 归一化到0-1区间
    img_array = np.expand_dims(img_array, axis=0)  # 增加batch维度
    predictions = model.predict(img_array)
    
    # 这里替换成你的模型结果解析逻辑,比如分类标签、置信度等
    return f"预测类别:{np.argmax(predictions[0])},置信度:{np.max(predictions[0]):.2f}"

@app.route("/", methods=["GET", "POST"])
def index():
    # 获取models目录下所有.h5模型文件
    available_models = [f for f in os.listdir(MODEL_DIR) if f.endswith(".h5")]
    inference_result = None

    if request.method == "POST":
        # 校验模型选择
        if "model_select" not in request.form or request.form["model_select"] == "":
            flash("请选择一个模型")
            return redirect(url_for("index"))
        selected_model = request.form["model_select"]

        # 校验图片上传
        if "image_upload" not in request.files:
            flash("请上传一张图片")
            return redirect(url_for("index"))
        file = request.files["image_upload"]
        if file.filename == "":
            flash("请选择要上传的图片文件")
            return redirect(url_for("index"))
        if file and allowed_file(file.filename):
            # 保存上传图片
            file_path = os.path.join(app.config["UPLOAD_FOLDER"], file.filename)
            file.save(file_path)

            # 执行推理
            try:
                model = load_selected_model(selected_model)
                inference_result = run_inference(model, file_path)
            except Exception as e:
                flash(f"推理出错:{str(e)}")
                return redirect(url_for("index"))

    return render_template("index.html", models=available_models, result=inference_result)

if __name__ == "__main__":
    app.run(debug=True)

前端页面(templates/index.html)

实现下拉选模型、图片上传、结果展示的交互:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>模型推理工具</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <div class="container">
        <h1>模型推理工具</h1>
        
        <!-- 显示错误提示 -->
        {% with messages = get_flashed_messages() %}
            {% if messages %}
                {% for msg in messages %}
                    <div class="alert alert-error">{{ msg }}</div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <!-- 交互表单 -->
        <form method="POST" enctype="multipart/form-data">
            <div class="form-item">
                <label for="model-select">选择模型:</label>
                <select id="model-select" name="model_select" required>
                    <option value="">请选择...</option>
                    {% for model in models %}
                        <option value="{{ model }}">{{ model }}</option>
                    {% endfor %}
                </select>
            </div>

            <div class="form-item">
                <label for="image-upload">上传图片:</label>
                <input type="file" id="image-upload" name="image_upload" accept="image/*" required>
            </div>

            <button type="submit" class="submit-btn">开始推理</button>
        </form>

        <!-- 展示推理结果 -->
        {% if result %}
            <div class="result-box">
                <h3>推理结果:</h3>
                <p>{{ result }}</p>
            </div>
        {% endif %}
    </div>
</body>
</html>

页面样式(static/css/style.css,可选)

简单美化页面,提升用户体验:

.container {
    max-width: 600px;
    margin: 50px auto;
    padding: 20px;
    font-family: Arial, sans-serif;
}

.form-item {
    margin-bottom: 20px;
}

label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
}

select, input[type="file"] {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.submit-btn {
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    cursor: pointer;
}

.submit-btn:hover {
    background-color: #0056b3;
}

.alert-error {
    background-color: #f8d7da;
    color: #721c24;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 20px;
}

.result-box {
    margin-top: 30px;
    padding: 15px;
    background-color: #d4edda;
    color: #155724;
    border-radius: 4px;
}

关键注意事项

  1. 安装依赖:执行pip install flask tensorflow pillow numpy安装所需库
  2. 模型适配:修改run_inference函数里的图片预处理逻辑,确保和你的模型训练时的参数一致(比如输入尺寸、归一化方式)
  3. 性能优化:如果模型体积大,可提前预加载所有模型到内存(需注意服务器内存占用),或添加模型缓存机制
  4. 生产环境:关闭debug=True,配置反向代理(如Nginx),并定期清理uploads/目录下的旧文件

内容的提问来源于stack exchange,提问作者Ram Sai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:16:36