作者|Aniket Maurya
編譯|VK
來源|Towards Datas Science
這個博客的源代碼可以從https://github.com/aniketmaurya/tensorflow-web-app-starter-pack獲得
讓我們從一個簡單的helloworld示例開始
首先,我們匯入FastAPI類并創建一個物件應用程式,這個類有一些有用的引數,比如我們可以傳遞swaggerui的標題和描述,
from fastapi import FastAPI
app = FastAPI(title='Hello world')
我們定義一個函式并用@app.get. 這意味著我們的API/index支持GET方法,這里定義的函式是異步的,FastAPI通過為普通的def函式創建執行緒池來自動處理異步和不使用異步方法,并且它為異步函式使用異步事件回圈,
@app.get('/index')
async def hello_world():
return "hello world"
影像識別API
我們將創建一個API來對影像進行分類,我們將其命名為predict/image,我們將使用Tensorflow來創建影像分類模型,
Tensorflow影像分類教程:https://aniketmaurya.ml/blog/tensorflow/deep learning/2019/05/12/image-classification-with-tf2.html
我們創建了一個函式load_model,它將回傳一個帶有預訓練權重的MobileNet CNN模型,即它已經被訓練為對1000個不同類別的影像進行分類,
import tensorflow as tf
def load_model():
model = tf.keras.applications.MobileNetV2(weights="imagenet")
print("Model loaded")
return model
model = load_model()
我們定義了一個predict函式,它將接受影像并回傳預測,我們將影像大小調整為224x224,并將像素值規格化為[-1,1],
from tensorflow.keras.applications.imagenet_utils
import decode_predictions
decode_predictions用于解碼預測物件的類名,這里我們將回傳前2個可能的類,
def predict(image: Image.Image):
image = np.asarray(image.resize((224, 224)))[..., :3]
image = np.expand_dims(image, 0)
image = image / 127.5 - 1.0
result = decode_predictions(model.predict(image), 2)[0]
response = []
for i, res in enumerate(result):
resp = {}
resp["class"] = res[1]
resp["confidence"] = f"{res[2]*100:0.2f} %"
response.append(resp)
return response
現在我們將創建一個支持檔案上傳的API/predict/image,我們將過濾檔案擴展名以僅支持jpg、jpeg和png格式的影像,
我們將使用Pillow加載上傳的影像,
def read_imagefile(file) -> Image.Image:
image = Image.open(BytesIO(file))
return image
@app.post("/predict/image")
async def predict_api(file: UploadFile = File(...)):
extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png")
if not extension:
return "Image must be jpg or png format!"
image = read_imagefile(await file.read())
prediction = predict(image)
return prediction
最終代碼
import uvicorn
from fastapi import FastAPI, File, UploadFile
from application.components import predict, read_imagefile
app = FastAPI()
@app.post("/predict/image")
async def predict_api(file: UploadFile = File(...)):
extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png")
if not extension:
return "Image must be jpg or png format!"
image = read_imagefile(await file.read())
prediction = predict(image)
return prediction
@app.post("/api/covid-symptom-check")
def check_risk(symptom: Symptom):
return symptom_check.get_risk_level(symptom)
if __name__ == "__main__":
uvicorn.run(app, debug=True)
FastAPI檔案是了解框架核心概念的最佳場所:https://fastapi.tiangolo.com/
希望你喜歡這篇文章,
原文鏈接:https://towardsdatascience.com/image-classification-api-with-tensorflow-and-fastapi-fc85dc6d39e8
歡迎關注磐創AI博客站:
http://panchuang.net/
sklearn機器學習中文官方檔案:
http://sklearn123.com/
歡迎關注磐創博客資源匯總站:
http://docs.panchuang.net/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/183401.html
標籤:其他
上一篇:通過正則化擴展回歸庫
下一篇:蒙特卡羅計算積分
