File size: 1,511 Bytes
1624b73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import cv2
import numpy as np
import os
from django.conf import settings
from ultralytics import YOLO

# Global model variable
_model = None

def get_model():
    global _model
    if _model is None:
        MODEL_PATH = os.path.join(settings.BASE_DIR, 'best.pt')
        try:
            _model = YOLO(MODEL_PATH)
        except Exception as e:
            print(f"Error loading model: {e}")
    return _model

def run_detection(image_path):
    """
    Runs YOLO detection on an image file path and returns a list of detections.
    """
    model = get_model()
    if model is None:
        return []

    img = cv2.imread(image_path)
    if img is None:
        return []

    results = model(img)
    detections = []
    
    for r in results:
        boxes = r.boxes
        for box in boxes:
            # Get coordinates in percentage for the frontend
            x_center, y_center, w, h = box.xywhn[0].tolist()
            
            x = (x_center - w/2) * 100
            y = (y_center - h/2) * 100
            width = w * 100
            height = h * 100
            
            conf = float(box.conf[0])
            cls = int(box.cls[0])
            label = model.names[cls]
            
            detections.append({
                "id": len(detections),
                "x": x,
                "y": y,
                "width": width,
                "height": height,
                "label": label,
                "confidence": conf * 100
            })
            
    return detections