The author | Aniket Maurya compile | source of vitamin k | forward Datas of Science

The source code for this blog is available at github.com/aniketmaury…

Let’s start with a simple HelloWorld example

First, we import the FastAPI class and create an object application. This class has some useful parameters, such as the title and description we can pass for Swaggerui.

from fastapi import FastAPI
app = FastAPI(title='Hello world')
Copy the code

We define a function and use @app.get. This means that our API/index supports get methods. The functions defined here are asynchronous, FastAPI handles asynchronous and non-asynchronous methods automatically by creating thread pools for normal DEF functions, and it uses asynchronous event loops for asynchronous functions.

@app.get('/index')
async def hello_world() :
    return "hello world"
Copy the code

Image recognition API

We will create an API to categorize the image, which we will call Predict/Image. We will use Tensorflow to create an image classification model.

Tensorflow image classification tutorial: aniketmaurya ml/blog/tensor…

We create a function load_model that will return a MobileNet CNN model with pre-trained weights, that is, it has been trained to classify 1000 different categories of images.

import tensorflow as tf

def load_model() :
    model = tf.keras.applications.MobileNetV2(weights="imagenet")
    print("Model loaded")
    return model
    
model = load_model()
Copy the code

We define a predict function that will accept the image and return the prediction. We resize the image to 224×224 and size the pixel value to [-1, 1].

from tensorflow.keras.applications.imagenet_utils 
import decode_predictions
Copy the code

Decode_predictions Class name used to decode predictions objects. Here we will return the first two possible classes.

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
Copy the code

Now we will create an API to support file uploads /predict/image. We will filter file extensions to support only JPG, JPEG, and PNG images.

We will use Pillow to load the uploaded image.

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
Copy the code

The final code

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)
Copy the code

The FastAPI documentation is the best place to learn the core concepts of the framework :fastapi.tiangolo.com/

Hope you enjoyed this article.

The original link: towardsdatascience.com/image-class…

Welcome to panchuangai blog: panchuang.net/

Sklearn123.com/

Welcome to docs.panchuang.net/