File size: 1,532 Bytes
4eed264
f2ff9e6
4eed264
f2ff9e6
4eed264
f2ff9e6
4eed264
 
 
 
f2ff9e6
 
4eed264
f2ff9e6
4eed264
 
a2b572d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eed264
f2ff9e6
4eed264
 
 
 
f2ff9e6
 
 
 
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
# Quick Inference with Ultralytics YOLO

This guide shows how to load a trained or pretrained YOLO model and run inference, returning the center coordinates of detected objects for class 0 and 1.

## Environment Setup

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install ultralytics
```

## Inference Example

```python
# 1. Load your model
from ultralytics import YOLO
model = YOLO('/absolute/path/to/weights/best.pt')
centers = get_centers_from_image(model, '/path/to/image.jpg')
print(centers)

def get_centers_from_image(model, image_path):
    results = model.predict(source=image_path, conf=0.15, classes=[0, 1])
    centers = {0: [], 1: []}
    try:
        for r in results:
            for box in r.boxes:
                cls = int(box.cls)
                if cls in [0, 1]:
                    x1, y1, x2, y2 = box.xyxy[0].tolist()
                    cx = (x1 + x2) / 2
                    cy = (y1 + y2) / 2
                    centers[cls].append((cx, cy))
        if not centers[0] and not centers[1]:
            return False
        return centers
    except Exception:
        return False
```

## Notes
- Replace `/absolute/path/to/weights/best.pt` with your trained or pretrained model path.
- Replace `/path/to/image/or/folder` with your image or folder path.
- The function `get_centers` returns a dictionary with lists of center coordinates for class 0 and 1.

## References
- [Ultralytics YOLO Docs](https://docs.ultralytics.com/)
- [YOLOv8 GitHub](https://github.com/ultralytics/ultralytics)