用pycharm实现一个图片识别页面,模型为自定义,类型为pth,具体实现代码
时间: 2024-06-09 18:07:06 浏览: 177
首先,我们需要安装必要的依赖包:
```
pip install flask torch torchvision pillow
```
接下来,我们创建一个名为 `app.py` 的文件,并将以下代码添加到文件中:
```python
import os
from flask import Flask, request, jsonify
from PIL import Image
import torch
import torchvision.transforms as transforms
app = Flask(__name__)
# 加载模型
model = torch.load('model.pth', map_location='cpu')
# 图像预处理
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
# 图片识别接口
@app.route('/predict', methods=['POST'])
def predict():
# 获取上传的图片
file = request.files['file']
img = Image.open(file.stream)
# 图片预处理
img_t = transform(img)
batch_t = torch.unsqueeze(img_t, 0)
# 预测图片类别
model.eval()
out = model(batch_t)
_, index = torch.max(out, 1)
label = index.tolist()[0]
# 返回结果
return jsonify({'label': label})
if __name__ == '__main__':
app.run()
```
在这个代码中,我们首先加载自定义模型(这里假设模型文件为 `model.pth`),然后定义了一个接口 `/predict`,用于接收 POST 请求并返回图片的识别结果。
接口的实现非常简单,我们首先获取上传的图片,然后对图片进行预处理,最后使用模型进行预测,并将结果返回给调用者。
最后,我们可以通过运行 `python app.py` 命令启动应用程序。当应用程序启动后,我们可以通过访问 `http://localhost:5000/predict` 接口来上传图片并获取识别结果。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)