Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import base64
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
from PIL import Image as PILImage
|
| 6 |
+
from ultralytics import YOLO
|
| 7 |
+
from fastapi import FastAPI, HTTPException
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
from typing import Optional
|
| 10 |
+
from matplotlib import cm
|
| 11 |
+
|
| 12 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 13 |
+
|
| 14 |
+
app = FastAPI()
|
| 15 |
+
|
| 16 |
+
# Add CORS middleware to allow requests from anywhere
|
| 17 |
+
app.add_middleware(
|
| 18 |
+
CORSMiddleware,
|
| 19 |
+
allow_origins=["*"], # Allow all origins
|
| 20 |
+
allow_credentials=True,
|
| 21 |
+
allow_methods=["*"], # Allow all HTTP methods
|
| 22 |
+
allow_headers=["*"], # Allow all headers
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
class ImageRequest(BaseModel):
|
| 26 |
+
image: str # Base64-encoded image string
|
| 27 |
+
|
| 28 |
+
class ObjectDetectionSystem:
|
| 29 |
+
def __init__(self, model_path='Model/yolov8l.pt'):
|
| 30 |
+
self.yolo_model = YOLO(model_path)
|
| 31 |
+
self.color_map = cm.get_cmap("tab20", len(self.yolo_model.names)) # Generate distinct colors
|
| 32 |
+
|
| 33 |
+
def detect_objects(self, image_base64: str, confidence_threshold: float = 0.5):
|
| 34 |
+
try:
|
| 35 |
+
# Decode Base64 and convert to NumPy array
|
| 36 |
+
image_data = base64.b64decode(image_base64)
|
| 37 |
+
pil_image = PILImage.open(io.BytesIO(image_data)).convert("RGB")
|
| 38 |
+
image_np = np.array(pil_image)
|
| 39 |
+
|
| 40 |
+
# Resize image for consistent processing
|
| 41 |
+
input_size = 640 # Example size for YOLO models
|
| 42 |
+
height, width, _ = image_np.shape
|
| 43 |
+
scale = input_size / max(height, width)
|
| 44 |
+
resized_image = cv2.resize(image_np, (int(width * scale), int(height * scale)))
|
| 45 |
+
|
| 46 |
+
# Perform object detection
|
| 47 |
+
results = self.yolo_model(resized_image)
|
| 48 |
+
|
| 49 |
+
# Draw results on image
|
| 50 |
+
output_image = resized_image.copy()
|
| 51 |
+
for result in results:
|
| 52 |
+
boxes = result.boxes
|
| 53 |
+
for box in boxes:
|
| 54 |
+
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
|
| 55 |
+
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
|
| 56 |
+
confidence = float(box.conf[0])
|
| 57 |
+
class_id = int(box.cls[0])
|
| 58 |
+
class_name = self.yolo_model.names[class_id]
|
| 59 |
+
|
| 60 |
+
if confidence > confidence_threshold:
|
| 61 |
+
# Generate color for this class
|
| 62 |
+
color = tuple(int(c * 255) for c in self.color_map(class_id)[:3])
|
| 63 |
+
|
| 64 |
+
# Draw bounding box
|
| 65 |
+
cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 2)
|
| 66 |
+
|
| 67 |
+
# Add label with confidence
|
| 68 |
+
label = f'{class_name} ({confidence:.2f})'
|
| 69 |
+
label_size, baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
|
| 70 |
+
label_y = max(y1, label_size[1] + 10)
|
| 71 |
+
cv2.rectangle(output_image, (x1, label_y - label_size[1] - 10),
|
| 72 |
+
(x1 + label_size[0], label_y + baseline - 10), color, -1)
|
| 73 |
+
cv2.putText(output_image, label, (x1, label_y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
|
| 74 |
+
|
| 75 |
+
# Convert back to Base64
|
| 76 |
+
output_pil = PILImage.fromarray(output_image)
|
| 77 |
+
buffered = io.BytesIO()
|
| 78 |
+
output_pil.save(buffered, format="PNG")
|
| 79 |
+
encoded_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 80 |
+
|
| 81 |
+
return encoded_image
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 85 |
+
|
| 86 |
+
# Initialize the detector with a more advanced model
|
| 87 |
+
detector = ObjectDetectionSystem('Model/yolov8l.pt')
|
| 88 |
+
|
| 89 |
+
@app.post("/detect")
|
| 90 |
+
async def detect_objects(request: ImageRequest):
|
| 91 |
+
try:
|
| 92 |
+
result_image = detector.detect_objects(request.image)
|
| 93 |
+
return {"processed_image": result_image}
|
| 94 |
+
except Exception as e:
|
| 95 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 96 |
+
|
| 97 |
+
@app.get("/")
|
| 98 |
+
async def root():
|
| 99 |
+
return {"message": "Object Detection API is running"}
|