Spaces:
Running
on
Zero
Running
on
Zero
Update models/detection/detector.py
Browse files- models/detection/detector.py +15 -3
models/detection/detector.py
CHANGED
@@ -3,6 +3,8 @@ import logging
|
|
3 |
from PIL import Image, ImageDraw
|
4 |
from huggingface_hub import hf_hub_download
|
5 |
|
|
|
|
|
6 |
class ObjectDetector:
|
7 |
def __init__(self, model_key="yolov8n", device="cpu"):
|
8 |
self.device = device
|
@@ -32,9 +34,9 @@ class ObjectDetector:
|
|
32 |
import torch # Safe to import here
|
33 |
from ultralytics import YOLO # Defer import
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
# Initialize model
|
39 |
self.model = YOLO(self.weights_path)
|
40 |
|
@@ -58,3 +60,13 @@ class ObjectDetector:
|
|
58 |
"bbox": box.xyxy[0].tolist()
|
59 |
})
|
60 |
return detections
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
from PIL import Image, ImageDraw
|
4 |
from huggingface_hub import hf_hub_download
|
5 |
|
6 |
+
logger = logging.getLogger(__name__)
|
7 |
+
|
8 |
class ObjectDetector:
|
9 |
def __init__(self, model_key="yolov8n", device="cpu"):
|
10 |
self.device = device
|
|
|
34 |
import torch # Safe to import here
|
35 |
from ultralytics import YOLO # Defer import
|
36 |
|
37 |
+
if self.device == "cpu":
|
38 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
39 |
+
|
40 |
# Initialize model
|
41 |
self.model = YOLO(self.weights_path)
|
42 |
|
|
|
60 |
"bbox": box.xyxy[0].tolist()
|
61 |
})
|
62 |
return detections
|
63 |
+
|
64 |
+
def draw(self, image: Image.Image, detections, alpha=0.5):
|
65 |
+
overlay = image.copy()
|
66 |
+
draw = ImageDraw.Draw(overlay)
|
67 |
+
for det in detections:
|
68 |
+
bbox = det["bbox"]
|
69 |
+
label = f'{det["class_name"]} {det["confidence"]:.2f}'
|
70 |
+
draw.rectangle(bbox, outline="red", width=2)
|
71 |
+
draw.text((bbox[0], bbox[1]), label, fill="red")
|
72 |
+
return Image.blend(image, overlay, alpha)
|