File size: 1,637 Bytes
bd152fb
 
 
 
 
 
e9b5166
bd152fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63d0d95
 
 
bd152fb
 
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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