📚博客主页:knighthood2001
✨公众号:认知up吧 (目前正在带领大家一起提升认知,感兴趣可以来围观一下)
🎃知识星球:【认知up吧|成长|副业】介绍
❤️如遇文章付费,可先看看我公众号中是否发布免费文章❤️
🙏笔者水平有限,欢迎各位大佬指点,相互学习进步!
假设,你有模型,有训练好的模型文件,有模型推理代码,就可以把他放到flask上进行展示。
项目架构
index.html
是模板文件app.py
是项目运行的入口best_model.pth
是训练好的模型参数model.py
是神经网络模型,这里采用的是GoogleNet网络。model_reasoning.py
是模型推理,通过这里面的代码,我们可以在本地进行猫狗图片的预测。
运行图
点击选择文件
图片下面就显示预测结果了。
项目完整代码与讲解
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图像分类</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#result {
margin-top: 10px;
}
#preview-image {
max-width: 400px;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>图像分类</h1>
<form id="upload-form" action="/predict" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*" onchange="previewImage(event)">
<input type="submit" value="预测">
</form>
<img id="preview-image" src="" alt="">
<br>
<div id="result"></div>
<script>
document.getElementById('upload-form').addEventListener('submit', async (e) => {
e.preventDefault(); // 阻止默认的表单提交行为
const formData = new FormData(); // 创建一个新的FormData对象,用于封装表单数据
formData.append('file', document.querySelector('input[type=file]').files[0]); // 添加表单数据
// 使用fetch API发送POST请求到'/predict'路径,并将formData作为请求体
const response = await fetch('/predict', {