Using a Pretrained Detection Model
Using the Ultralytics YOLOv8 library for quick and accurate object detection.
10 min•By Priygop Team•Updated 2026
YOLOv8 with Ultralytics
YOLOv8 with Ultralytics
# Installation: pip install ultralytics
from ultralytics import YOLO
import cv2
def detect_with_yolov8(image_path, output_path="yolo_result.jpg",
confidence=0.5, iou_threshold=0.45):
"""
Run YOLOv8 object detection on an image.
First run: automatically downloads the pretrained model.
"""
# Load YOLOv8 nano model (fastest, good for learning)
# Options: yolov8n, yolov8s, yolov8m, yolov8l, yolov8x (nano to xlarge)
model = YOLO("yolov8n.pt") # Downloads ~6MB on first run
# Run detection
results = model(
image_path,
conf=confidence, # Confidence threshold
iou=iou_threshold # IoU threshold for NMS
)
print(f"=== YOLOv8 Detection Results ===")
for result in results:
boxes = result.boxes
print(f"Detected {len(boxes)} objects:")
for box in boxes:
class_id = int(box.cls[0])
class_name = model.names[class_id]
conf = float(box.conf[0])
x1, y1, x2, y2 = box.xyxy[0].tolist()
print(f" {class_name}: {conf:.2%} at ({x1:.0f},{y1:.0f}) to ({x2:.0f},{y2:.0f})")
# Save annotated image
annotated = result.plot() # Returns numpy array with annotations
cv2.imwrite(output_path, annotated)
print(f"Saved: {output_path}")
detect_with_yolov8("photo.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment