File size: 899 Bytes
38d4385
 
 
 
890b83b
38d4385
 
 
 
 
 
 
 
 
890b83b
38d4385
fba92a9
890b83b
 
 
38d4385
 
 
890b83b
fba92a9
 
38d4385
890b83b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import numpy as np
from fastapi import FastAPI, File, UploadFile
import tensorflow as tf
from PIL import Image
from io import BytesIO

app = FastAPI()

labels = []
model = tf.keras.models.load_model('./models.h5')
with open("labels.txt") as f:
    for line in f:
        labels.append(line.replace('\n', ''))

def classify_image(img):
    # Resize the input image to the expected shape (224, 224)
    img_array = np.asarray(img.resize((224, 224)))[..., :3]
    img_array = img_array.reshape((-1, 224, 224, 3))
    img_array = tf.keras.applications.efficientnet.preprocess_input(img_array)
    prediction = model.predict(img_array).flatten()
    confidences = {labels[i]: float(prediction[i]) for i in range(90)}
    return confidences

@app.post("/predict")
async def predict(file: bytes = File(...)):
    img = Image.open(BytesIO(file))
    confidences = classify_image(img)
    return confidences