Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File
|
2 |
+
from transformers import pipeline
|
3 |
+
from PIL import Image
|
4 |
+
import io
|
5 |
+
|
6 |
+
# Initialize the FastAPI app
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
# Load the YOLOv5 model for object detection
|
10 |
+
detector = pipeline('object-detection', model='ultralytics/yolov5')
|
11 |
+
|
12 |
+
@app.post("/detect_objects/")
|
13 |
+
async def detect_objects(file: UploadFile = File(...)):
|
14 |
+
# Read image from uploaded file
|
15 |
+
image_bytes = await file.read()
|
16 |
+
image = Image.open(io.BytesIO(image_bytes))
|
17 |
+
|
18 |
+
# Perform object detection
|
19 |
+
results = detector(image)
|
20 |
+
|
21 |
+
# Extract bounding box coordinates and labels
|
22 |
+
bounding_boxes = []
|
23 |
+
for result in results:
|
24 |
+
box = result['box']
|
25 |
+
bbox = {
|
26 |
+
'label': result['label'],
|
27 |
+
'confidence': result['score'],
|
28 |
+
'x_min': box['xmin'],
|
29 |
+
'y_min': box['ymin'],
|
30 |
+
'x_max': box['xmax'],
|
31 |
+
'y_max': box['ymax']
|
32 |
+
}
|
33 |
+
bounding_boxes.append(bbox)
|
34 |
+
|
35 |
+
# Return bounding box coordinates as response
|
36 |
+
return {"bounding_boxes": bounding_boxes}
|
37 |
+
|
38 |
+
# To run the server, use: uvicorn app:app --reload
|