bt_fastapi / app.py
pavankm96's picture
Update app.py
e9b5166 verified
Raw History Blame Contribute Delete
1.64 kB
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from PIL import Image
import numpy as np
import cv2
import tensorflow as tf # Assuming you're using TensorFlow for loading your model
app = FastAPI()
# Load your model
model = tf.keras.models.load_model("Brain_tumor_pred_large.h5")
def predict_tumor(image: Image.Image):
# Convert the PIL image to OpenCV format
opencv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
img = cv2.resize(opencv_image, (128, 128))
img = img.reshape(1, 128, 128, 3)
# Predict using the model
predictions = model.predict(img)[0] # Get probabilities for each class
predicted_class = np.argmax(predictions) # Index of the predicted class
confidence = predictions[predicted_class] # Confidence of the predicted class
# Determine if a tumor is present
if confidence < 0.20:
if confidence < 0.10:
result = "No Tumor"
confidence = 1.0
else:
result = "Uncertain"
else:
result = "No Tumor" if predicted_class == 1 else "Tumor Detected"
return {"result": result, "confidence": f"{confidence:.2%}"}
@app.post("/predict")
async def predict(upload: UploadFile = File(...)):
try:
# Open and process the uploaded image file
image = Image.open(upload.file)
result = predict_tumor(image)
return JSONResponse(content=result)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# To run the FastAPI app, use the following command:
# uvicorn app:app --reload