后端:flask+polar+pytorch
后端采用flask,把自己的电脑作为服务器,开放5000端口
代码直接用:
使用Flask来部署PyTorch模型 - PyTorch官方教程中文版 (panchuang.net)
使用polar内网穿透:
(19条消息) 个人电脑秒变服务器 简单几步,你的电脑也可以成为服务器 (内网穿透)_小王不头秃的博客-CSDN博客_把自己电脑变成服务器
具体代码和文件:(一个app.py,一个imagenet_class_index.json,使用cors解决跨域问题)
(31条消息) 将pytorch模型部署到服务器(自己电脑)flask-深度学习文档类资源-CSDN文库
import io
import json
from torchvision import models
import torchvision.transforms as transforms
from PIL import Image
from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources=r'/*')
imagenet_class_index = json.load(open('./imagenet_class_index.json'))
model = models.densenet121(pretrained=True)
model.eval()
def transform_image(image_bytes):
my_transforms = transforms.Compose([transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
[0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])])
image = Image.open(io.BytesIO(image_bytes))
return my_transforms(image).unsqueeze(0)
def get_prediction(image_bytes):
tensor = transform_image(image_bytes=image_bytes)
outputs = model.forward(tensor)
_, y_hat = outputs.max(1)
predicted_idx = str(y_hat.item())
return imagenet_class_index[predicted_idx]
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
file = request.files['file']
img_bytes = file.read()
class_id, class_name = get_prediction(image_bytes=img_bytes)
return jsonify({'class_id': class_id, 'class_name': class_name})
if __name__ == '__main__':
app.run()
前端:uniapp
前端采用uniapp,发送post请求,直接把图片发送给后端
<template>
<view>
<input type="text" value="" v-model="username" placeholder="账号"/>
<input type="text" value="" v-model="password" placeholder="密码"/>
<!-- <button type="default" @click="request()">发起请求</button> -->
<button type="default" @click="request()">发起请求/登录</button>
<button type="default" @click="upload()">上传图片</button>
<view class="arrow-area">
{{msg}} <br>
</view>
<button type="default" @click="nextPage()">进入个人中心</button>
</view>
</template>
<script>
export default {
data() {
return {
"msg":'显示信息',
"nickName": '',
"age":20,
"email":'',
"id":'',
"username":"",
"password":"",
}
},
methods: {
request(){
var that = this
uni.request({
method:'POST',
header: {
// json数据的发送
// "content-type": "application/json",
// 键值对形式数据发送
"content-type": "application/x-www-form-urlencoded",
"source": "fromApp",
// "Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MjEsInVzZXJuYW1lIjoiMjIyMjIyIiwicGFzc3dvcmQiOiIiLCJuaWNrbmFtZSI6bnVsbCwiZW1haWwiOm51bGwsInVzZXJfcGljIjoiIiwiaWF0IjoxNjU5OTQyODg0LCJleHAiOjE2NTk5Nzg4ODR9.-7TwtvLhXkU_iGJ9HnSG8K4vSRlUFj1mie1O-EeKU5Q"
},
// dataType:JSON,
// url:'http://http://111.67.196.136:80/api/reguser',
// url:'http://127.0.0.1:3007/api/login',
// url:'http://127.0.0.1:3007/my/userinfo',
url:'http://127.0.0.1:5000/predict',
data:{
// "message" :that.msg ,
// "nickName": "zs",
// "age":20,
// "username":that.username,
// "password":that.password,
},
success:(res)=> {
console.log('请求成功!success')
console.log(res.data)
// that.msg =JSON.stringify(res.data)
that.msg =res.data
// that.nickName =res.data.data.nickname
// that.username =res.data.data.username
// that.id =res.data.data.id
var token = res.data.token
// console.log(token)
uni.setStorageSync('token',token)
}
})
},
nextPage(){
uni.navigateTo({
url:'video_play'
})
},
upload(){
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
uni.uploadFile({
// url: 'http://127.0.0.1:5000/predict', //仅为示例,非真实的接口地址,
url: 'http://7c8087d8.r3.cpolar.top/predict',//cpolar开放5000端口
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success: (uploadFileRes) => {
console.log(uploadFileRes.data);
this.msg = uploadFileRes.data
console.log('预测结束!结果已返回')
}
});
}
});
}
}
}
</script>
<style>
</style>
结果
选了家里的小狗狗:
cmd返回200,说明请求成功
前端返回分类结果: