SegMedDA2 / detect.py
ziuwuchuoi
26/6 test bbox
87e1545
Raw History Blame Contribute Delete
1.95 kB
#main.py
from fastapi import FastAPI, UploadFile, File, HTTPException, Body, Form
from PIL import Image
import cv2
import numpy as np
import os
from ultralytics import YOLO
import torch
from PIL import Image
from io import BytesIO
import shutil
import base64
# Set environment variables for cache directories
os.environ['HF_HOME'] = '/code/cache/huggingface/hub'
os.environ['TRANSFORMERS_CACHE'] = '/code/cache/images'
model = YOLO('ckpt/best.pt')
app = FastAPI()
def Tumor_detect(img_path):
print("Processing image:", img_path)
# Read the image
img = cv2.imread(img_path)
print("img", img)
# Pass the image through the detection model and get the result
detect_result = model(img)
print("detect_result", detect_result)
print("detect_result[0]", detect_result[0])
# Plot the detections
detect_img = detect_result[0].plot()
print("detect_img", detect_img)
# Convert the image to RGB format
detect_img = cv2.cvtColor(detect_img, cv2.COLOR_BGR2RGB)
print("detect_img", detect_img)
return detect_img
def encode_image_to_base64(image):
_, buffer = cv2.imencode('.jpg', image)
encoded_image = base64.b64encode(buffer).decode('utf-8')
return encoded_image
@app.post("/detect")
async def detect(image: UploadFile = File(...)):
try:
print("image", image)
temp_dir = "static"
temp_file_path = os.path.join(temp_dir, image.filename)
with open(temp_file_path, "wb") as buffer:
shutil.copyfileobj(image.file, buffer)
# Perform tumor detection
# Perform tumor detection
result_img = Tumor_detect(temp_file_path)
# Encode the result image to base64
encoded_result_img = encode_image_to_base64(result_img)
# Return the base64-encoded image as JSON response
return encoded_result_img
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))