Object Detection with YOLO (Ultralytics)
This guide demonstrates how to perform object detection using the YOLO (You Only Look Once) model via the ultralytics library. YOLO is known for its speed and accuracy in real-time object detection.
Modules Used:
ultralytics: The official Python package for YOLOv8 (and newer).- argparse: To handle command-line arguments.
Installation
pip install ultralytics
The Code
Save this as object_detect.py.
from ultralytics import YOLO
import argparse
import sys
import os
def detect_objects(image_path, model_name='yolov8n.pt', show=False, save=True):
if not os.path.exists(image_path):
print(f"Error: Image '{image_path}' not found.")
return
print(f"Loading model '{model_name}'...")
try:
# Load a pretrained YOLO model
# yolov8n.pt is the "nano" version (fastest, least accurate)
# Other options: yolov8s.pt, yolov8m.pt, yolov8l.pt, yolov8x.pt
# The weights will be downloaded automatically if not found locally.
model = YOLO(model_name)
except Exception as e:
print(f"Error loading model: {e}")
return
print(f"Processing '{image_path}'...")
# Perform inference
# save=True saves the annotated image to 'runs/detect/predict/'
# show=True displays the image in a window
results = model(image_path, save=save, show=show)
# Results is a list (one for each image passed)
for result in results:
boxes = result.boxes
print(f"\nDetected {len(boxes)} objects:")
# Summary of detections
for box in boxes:
# Class ID
cls_id = int(box.cls[0])
# Class Name
cls_name = model.names[cls_id]
# Confidence Score
conf = float(box.conf[0])
print(f" - {cls_name} ({conf:.2f})")
if save:
print(f"\nResults saved to directory: {results[0].save_dir}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="YOLO Object Detection")
parser.add_argument("image", help="Path to the input image")
parser.add_argument("--model", default="yolov8n.pt", help="YOLO model to use (default: yolov8n.pt)")
parser.add_argument("--show", action="store_true", help="Display the result in a window")
parser.add_argument("--no-save", action="store_true", help="Do not save the annotated image")
args = parser.parse_args()
detect_objects(args.image, args.model, args.show, not args.no_save)
Usage
# Detect objects in an image using the default Nano model
python object_detect.py street.jpg
# Use a larger model (Medium) and display the result
python object_detect.py street.jpg --model yolov8m.pt --show