关于人工智能:用Tensorflow和FastAPI构建图像分类API

8次阅读

共计 2423 个字符,预计需要花费 7 分钟才能阅读完成。

作者 |Aniket Maurya
编译 |VK
起源 |Towards Datas Science

这个博客的源代码能够从 https://github.com/aniketmaur…

让咱们从一个简略的 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/…

咱们创立了一个函数 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 函数,它将承受图像并返回预测。咱们将图像大小调整为 224×224,并将像素值规格化为 [-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.co…

欢送关注磐创 AI 博客站:
http://panchuang.net/

sklearn 机器学习中文官网文档:
http://sklearn123.com/

欢送关注磐创博客资源汇总站:
http://docs.panchuang.net/

正文完
 0