Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from transformers import pipeline, YolosForObjectDetection, YolosImageProcessor
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
# Create a new FastAPI app instance
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# Initialize the Yolos model and image processor
|
| 11 |
+
yolos_model = YolosForObjectDetection.from_pretrained('hustvl/yolos-tiny')
|
| 12 |
+
yolos_image_processor = YolosImageProcessor.from_pretrained("hustvl/yolos-tiny")
|
| 13 |
+
|
| 14 |
+
# Route for object detection using Yolos model
|
| 15 |
+
@app.get("/detect-objects")
|
| 16 |
+
def detect_objects(url: str):
|
| 17 |
+
# Download the image from the specified URL
|
| 18 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 19 |
+
|
| 20 |
+
# Preprocess the image using the Yolos image processor
|
| 21 |
+
inputs = yolos_image_processor(images=image, return_tensors="pt")
|
| 22 |
+
|
| 23 |
+
# Run the Yolos model on the preprocessed image
|
| 24 |
+
outputs = yolos_model(**inputs)
|
| 25 |
+
|
| 26 |
+
# model predicts bounding boxes and corresponding COCO classes
|
| 27 |
+
logits = outputs.logits
|
| 28 |
+
pred_boxes = outputs.pred_boxes
|
| 29 |
+
|
| 30 |
+
# Post-process the object detection results
|
| 31 |
+
target_sizes = torch.tensor([image.size[::-1]])
|
| 32 |
+
results = yolos_image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[0]
|
| 33 |
+
|
| 34 |
+
# Format and return the results
|
| 35 |
+
detected_objects = []
|
| 36 |
+
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
| 37 |
+
box = [round(i, 2) for i in box.tolist()]
|
| 38 |
+
detected_objects.append({
|
| 39 |
+
"label": yolos_model.config.id2label[label.item()],
|
| 40 |
+
"confidence": round(score.item(), 3),
|
| 41 |
+
"location": box
|
| 42 |
+
})
|
| 43 |
+
|
| 44 |
+
return {"detected_objects": detected_objects}
|