I would like to create a FastAPI application for my image classification model. But when I upload the image file, it can not make predictions, because my model is setting the image as (256,256)
, but the image that gets uploaded is not (256,256)
. How can I resize the image after uploading and before getting predictions?
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import numpy as np
from io import BytesIO
from PIL import Image
import tensorflow as tf
app = FastAPI()
MODEL = tf.keras.models.load_model("D:/Works/M.6/New Soil/Classification/Model/SoilModel.h5")
CLASS_NAMES = ["Clay", "Loam", "Red","Sandy"]
@app.get("/home")
async def ping():
return "Hello, Welcome to CropChat"
def read_file_as_image(data) -> np.ndarray:
image = np.array(Image.open(BytesIO(data)))
return image
@app.post("/predict")
async def predict(
file: UploadFile = File(...)
):
image = read_file_as_image(await file.read())
img_batch = np.expand_dims(image, 0)
predictions = MODEL.predict(img_batch)
predicted_class = CLASS_NAMES[np.argmax(predictions[0])]
confidence = np.max(predictions[0])
return {
'class': predicted_class,
'confidence': float(confidence)
}
if __name__ == "__main__":
uvicorn.run(app, host='localhost', port=8000)
I tried to use image.resize
, but it doesn't work.
If you guys have some recommendations for my code please let me know. Thank you.