使用Flask部署肺炎预测模型时浏览器无结果且报文件找不到错误
问题修复方案
核心问题分析
- 本地文件访问导致路径错误:直接在本地打开
index.html(file://协议)时,表单提交会尝试在本地目录寻找predict文件,而非发送请求到Flask服务器。必须通过Flask启动的HTTP服务(如http://localhost:5000)访问页面。 - 无响应返回+服务器端绘图无效:
predict函数未返回任何HTTP响应,且plt.show()仅在服务器本地弹出窗口,浏览器无法获取结果。
修复步骤
1. 调整项目结构
创建templates文件夹,将index.html移入其中,最终结构:
m3cad/ ├── detect.py ├── model12.h5 └── templates/ └── index.html
2. 修改detect.py代码
修复路由逻辑、图片处理流程,将预测结果返回前端:
from flask import Flask, request, render_template import numpy as np from tensorflow.keras.utils import img_to_array from tensorflow.keras.models import load_model from PIL import Image import io # 加载训练好的模型 model = load_model('model12.h5') # 初始化Flask应用 app = Flask(__name__) # 根路由:渲染图片上传页面 @app.route('/') def index(): return render_template('index.html') # 预测路由:处理上传请求并返回结果 @app.route('/predict', methods=['POST']) def predict(): # 读取上传的图片文件 image_file = request.files['image-file'] # 使用PIL处理图片,兼容更多格式 image = Image.open(image_file.stream).convert('RGB') # 预处理图片(需匹配模型训练时的输入尺寸,示例为224x224,根据你的模型调整) image = image.resize((224, 224)) test_image = img_to_array(image) test_image = np.expand_dims(test_image, axis=0) # 归一化(与模型训练时的预处理逻辑一致,示例为除以255) test_image = test_image / 255.0 # 执行预测 pred = model.predict(test_image) predict_idx = np.argmax(pred, axis=-1) # 生成预测结果文本 prediction = 'Normal' if predict_idx == 0 else 'Pneumonia +VE' confidence = f"{np.max(pred)*100:.2f}%" # 将结果返回至前端页面 return render_template('index.html', prediction=prediction, confidence=confidence) # 启动Flask服务 if __name__ == '__main__': app.run(debug=True)
3. 修改index.html添加结果展示
在表单下方增加预测结果显示区域:
<!DOCTYPE html> <html> <head> <title>肺炎图像预测</title> </head> <body> <h1>肺炎图像预测</h1> <form action="/predict" method="post" enctype="multipart/form-data"> <div> <label for="image-file">选择图像文件:</label> <input type="file" name="image-file" accept="image/*" required /> </div> <div style="margin-top:10px;"> <input type="submit" value="开始预测" /> </div> </form> <!-- 预测结果展示区域 --> {% if prediction %} <div style="margin-top:20px; padding:10px; border:1px solid #ccc;"> <h2>预测结果: {{ prediction }}</h2> <p>置信度: {{ confidence }}</p> </div> {% endif %} </body> </html>
4. 运行与访问
- 安装依赖包:
pip install flask tensorflow pillow numpy - 运行
detect.py,终端会显示服务地址(如http://127.0.0.1:5000) - 在浏览器中打开该地址,上传图片即可查看预测结果
内容的提问来源于stack exchange,提问作者Maaz
相关产品推荐
相关产品推荐

