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

Flask图像预测项目报错无法输出结果 附前后端代码求助

问题排查及修复方案

1. 前端缺少表单提交逻辑

你的预测按钮是独立于表单的普通按钮,点击后不会触发表单提交,自然不会发请求到后端预测接口,两种修复方案选一种即可:

方案A:简单表单提交(无需JS)

把预测按钮挪到form标签内部,修改type为submit,同时给form加action属性指向/predict:

<form id="upload-file" method="post" enctype="multipart/form-data" action="/predict">
    <label for="imageUpload" class="upload-label">
        Choose...
    </label>
    <input type="file" name="file" id="imageUpload" accept=".png, .jpg, .jpeg">
    <div>
        <button type="submit" class="btn btn-primary btn-lg " id="btn-predict">Predict!</button>
    </div>
</form>

方案B:AJAX无刷新提交(体验更好)

在HTML末尾加一段JS逻辑,绑定按钮点击事件,提交表单后把结果回填到结果区域:

<script>
document.getElementById('btn-predict').addEventListener('click', function () {
    const formData = new FormData(document.getElementById('upload-file'));
    fetch('/predict', {
        method: 'POST',
        body: formData
    })
    .then(res => res.text())
    .then(data => {
        document.querySelector('#result span').textContent = data;
    })
    .catch(err => console.error('预测出错:', err));
});
</script>

2. 后端缺少uploads目录校验

如果你的项目根目录下没有手动创建uploads文件夹,保存上传文件时会抛出路径不存在的异常,在保存文件前加目录创建逻辑,修改后的完整upload路由如下:

@app.route('/predict', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)
        upload_dir = os.path.join(basepath, 'uploads')
        # 新增目录校验创建
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)
        file_path = os.path.join(upload_dir, secure_filename(f.filename))
        f.save(file_path)
        preds = model_predict(file_path, model)
        return preds
    # 处理GET请求,直接返回首页
    return redirect('/')

3. 预处理一致性校验

确认你训练model_resnet50.h5时的预处理逻辑和预测时一致:

  • 如果你训练时用了preprocess_input做归一化,就删掉预测代码里的x=x/255,替换成x = preprocess_input(x)
  • 确保训练时输入尺寸也是224*224,分类数为3,标签顺序确实是0=Dhoni、1=Kohli、2=Rohith

4. 其他常见问题排查

  • 确认model_resnet50.h5文件放在项目根目录下,和启动文件路径一致
  • 启动项目后看控制台报错信息,若有模型加载错误,检查TensorFlow版本和训练模型时的版本是否兼容,大版本不一致容易出现加载失败问题

内容的提问来源于stack exchange,提问作者cheppalli abhishek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:06:02