5. Apply a yolo object detection algorithm for real
world problem.
from ultralytics import YOLO
import cv2
model = YOLO("yolov8n.pt") # 'n' = nano model (fastest
and lightweight)
image_path = "sample.jpg" # Replace with your image
path
img = cv2.imread(image_path)
results = model(image_path)
for result in results:
boxes = result.boxes
for box in boxes:
# Extract box coordinates
x1, y1, x2, y2 = map(int, box.xyxy[0])
conf = box.conf[0].item() # confidence
cls = int(box.cls[0]) # class id
label = model.names[cls]
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, f"{label} {conf:.2f}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,
0, 0), 2)
cv2.imshow("YOLO Object Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
