Spaces:
Sleeping
Sleeping
Create identification_model.py
Browse files- identification_model.py +35 -0
identification_model.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from ultralytics import YOLO
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
def load_yolov8_model():
|
| 7 |
+
# Load the YOLOv8 model
|
| 8 |
+
model = YOLO('yolov8n.pt') # Using the smallest version for speed; adjust as needed
|
| 9 |
+
return model
|
| 10 |
+
|
| 11 |
+
def run_object_detection(model, image_path):
|
| 12 |
+
# Load the image
|
| 13 |
+
image = Image.open(image_path).convert('RGB')
|
| 14 |
+
image_np = np.array(image)
|
| 15 |
+
|
| 16 |
+
# Run inference
|
| 17 |
+
results = model(image_np)
|
| 18 |
+
|
| 19 |
+
# Process results
|
| 20 |
+
detections = []
|
| 21 |
+
for result in results:
|
| 22 |
+
boxes = result.boxes
|
| 23 |
+
for box in boxes:
|
| 24 |
+
x1, y1, x2, y2 = box.xyxy[0].tolist() # Bounding box coordinates
|
| 25 |
+
conf = box.conf[0].item() # Confidence score
|
| 26 |
+
cls = int(box.cls[0].item()) # Class ID
|
| 27 |
+
label = model.names[cls] # Class name
|
| 28 |
+
|
| 29 |
+
detections.append({
|
| 30 |
+
'box': [x1, y1, x2, y2],
|
| 31 |
+
'confidence': conf,
|
| 32 |
+
'label': label
|
| 33 |
+
})
|
| 34 |
+
|
| 35 |
+
return detections
|