Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -31,6 +31,20 @@ def detect_objects(url: str):
|
|
| 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"]):
|
|
@@ -41,4 +55,7 @@ def detect_objects(url: str):
|
|
| 41 |
"location": box
|
| 42 |
})
|
| 43 |
|
| 44 |
-
return {"detected_objects": detected_objects}
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Draw bounding boxes on the image
|
| 35 |
+
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
| 36 |
+
image_draw = ImageDraw.Draw(image)
|
| 37 |
+
image_draw.rectangle(box.tolist(), outline="red", width=2)
|
| 38 |
+
image_draw.text((box[0], box[1]), f"{yolos_model.config.id2label[label.item()]}: {round(score.item(), 3)}", fill="red")
|
| 39 |
+
|
| 40 |
+
# Save the modified image to a byte stream
|
| 41 |
+
image_byte_array = io.BytesIO()
|
| 42 |
+
image.save(image_byte_array, format="PNG")
|
| 43 |
+
|
| 44 |
+
# Encode the byte stream as a base64 string
|
| 45 |
+
image_base64 = base64.b64encode(image_byte_array.getvalue()).decode("utf-8")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
# Format and return the results
|
| 49 |
detected_objects = []
|
| 50 |
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
|
|
|
| 55 |
"location": box
|
| 56 |
})
|
| 57 |
|
| 58 |
+
return {"detected_objects": detected_objects, "image_base64": image_base64}
|
| 59 |
+
|
| 60 |
+
except Exception as e:
|
| 61 |
+
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
|