quocanh34's picture
Update README.md
a2b572d verified
# 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)