Flask之最易懂的基礎教程一(2020年最新-從入門到精通)-CSDN博客
Flask程序運行過程:
所有Flask程序必須有一個程序實例。
Flask調用視圖函數(shù)后,會將視圖函數(shù)的返回值作為響應的內容,返回給客戶端。一般情況下,響應內容主要是字符串和狀態(tài)碼。
用戶向瀏覽器發(fā)送http請求,web服務器把客戶端所有請求交給Flask程序實例,程序用Werkzeug來做路由分發(fā),每個url請求,找到具體的視圖函數(shù)。路由的實現(xiàn)是通過route裝飾器實現(xiàn)的,調用視圖函數(shù),獲取數(shù)據(jù)后,把數(shù)據(jù)傳入模塊中,模塊引擎渲染響應的數(shù)據(jù),由Flask返回給瀏覽器。
?文章來源:http://www.zghlxwxcb.cn/news/detail-852047.html
二、Flask框架
1. 簡介
是一個非常小的框架,可以稱為微型框架,只提供了一個強勁的核心,其他的功能都需要使用拓展來實現(xiàn)。意味著可以根據(jù)自己的需求量身打造;
2. 組成
調試、路由、wsgi系統(tǒng)
模板引擎(Jinja2)
3. 安裝
pip install flask文章來源地址http://www.zghlxwxcb.cn/news/detail-852047.html
響應端? flask_server.py
import io
import json
import flask
import torch
import torch
import torch.nn.functional as F
from PIL import Image
from torch import nn
#from torchvision import transforms as T
from torchvision import transforms, models, datasets
from torch.autograd import Variable
# 初始化Flask app
app = flask.Flask(__name__)
model = None
use_gpu = False
# 加載模型進來
def load_model():
"""Load the pre-trained model, you can use your model just as easily.
"""
global model
#這里我們直接加載官方工具包里提供的訓練好的模型(代碼會自動下載)括號內參數(shù)為是否下載模型對應的配置信息
model = models.resnet18()
num_ftrs = model.fc.in_features
model.fc = nn.Sequential(nn.Linear(num_ftrs, 102)) # 類別數(shù)自己根據(jù)自己任務來
#print(model)
checkpoint = torch.load('best.pth')
model.load_state_dict(checkpoint['state_dict'])
#將模型指定為測試格式
model.eval()
#是否使用gpu
if use_gpu:
model.cuda()
# 數(shù)據(jù)預處理
def prepare_image(image, target_size):
"""Do image preprocessing before prediction on any data.
:param image: original image
:param target_size: target image size
:return:
preprocessed image
"""
#針對不同模型,image的格式不同,但需要統(tǒng)一至RGB格式
if image.mode != 'RGB':
image = image.convert("RGB")
# Resize the input image and preprocess it.(按照所使用的模型將輸入圖片的尺寸修改,并轉為tensor)
image = transforms.Resize(target_size)(image)
image = transforms.ToTensor()(image)
# Convert to Torch.Tensor and normalize. mean與std (RGB三通道)這里的參數(shù)和數(shù)據(jù)集中是對應的,訓練過程中一致
image = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])(image)
# Add batch_size axis.增加一個維度,用于按batch測試 本次這里一次測試一張
image = image[None]
if use_gpu:
image = image.cuda()
return Variable(image, volatile=True) #不需要求導
# 開啟服務 這里的predict只是一個名字,可自定義
@app.route("/predict", methods=["POST"])
def predict():
# Initialize the data dictionary that will be returned from the view.
#做一個標志,剛開始無圖像傳入時為false,傳入圖像時為true
data = {"success": False}
# 如果收到請求
if flask.request.method == 'POST':
#判斷是否為圖像
if flask.request.files.get("image"):
# Read the image in PIL format
# 將收到的圖像進行讀取
image = flask.request.files["image"].read()
image = Image.open(io.BytesIO(image)) #二進制數(shù)據(jù)
# 利用上面的預處理函數(shù)將讀入的圖像進行預處理
image = prepare_image(image, target_size=(64, 64))
preds = F.softmax(model(image), dim=1)
results = torch.topk(preds.cpu().data, k=3, dim=1)
results = (results[0].cpu().numpy(), results[1].cpu().numpy())
#將data字典增加一個key,value,其中value為list格式
data['predictions'] = list()
# Loop over the results and add them to the list of returned predictions
for prob, label in zip(results[0][0], results[1][0]):
#label_name = idx2label[str(label)]
r = {"label": str(label), "probability": float(prob)}
#將預測結果添加至data字典
data['predictions'].append(r)
# Indicate that the request was a success.
data["success"] = True
# 將最終結果以json格式文件傳出
return flask.jsonify(data)
"""
test_json = {
"status_code": 200,
"success": {
"message": "image uploaded",
"code": 200
},
"video":{
"video_name":opt['source'].split('/')[-1],
"video_path":opt['source'],
"description":"1",
"length": str(hour)+','+str(minute)+','+str(round(second,4)),
"model_object_completed":model_flag
}
"status_txt": "OK"
}
response = requests.post(
'http://xxx.xxx.xxx.xxx:8090/api/ObjectToKafka/',,
data={'json': str(test_json)})
"""
if __name__ == '__main__':
print("Loading PyTorch model and Flask starting server ...")
print("Please wait until server has fully started")
#先加載模型
load_model()
#再開啟服務
app.run(port='5012')
?請求端? flask_predict.py
import requests
import argparse
# url和端口攜程自己的
flask_url = 'http://127.0.0.1:5012/predict'
def predict_result(image_path):
#啥方法都行
image = open(image_path, 'rb').read()
payload = {'image': image}
#request發(fā)給server.
r = requests.post(flask_url, files=payload).json()
# 成功的話在返回.
if r['success']:
# 輸出結果.
for (i, result) in enumerate(r['predictions']):
print('{}. {}: {:.4f}'.format(i + 1, result['label'],
result['probability']))
# 失敗了就打印.
else:
print('Request failed')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Classification demo')
parser.add_argument('--file', default=r'D:\paogu\flask預測\flower_data\train\1\image_06734.jpg', type=str, help='test image file')
args = parser.parse_args()
predict_result(args.file)
到了這里,關于基于Flask測試深度學習模型預測的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!