Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Object Detection with YOLOv8: Using a Pre-Trained Model on Images

1 min read .
Object Detection with YOLOv8: Using a Pre-Trained Model on Images

In this article, we will experiment with YOLOv8 for object detection in images. YOLO (You Only Look Once) is one of the best-known object detection algorithms. YOLOv8 offers fast performance and accurate results. Fortunately, the ultralytics library makes it straightforward to use.

What You Need

Before you begin, make sure you have:

  • Python
  • The ultralytics library

If it is not installed yet, install it with pip:

pip install ultralytics

Simple Code Example

Here is a short example that detects objects with YOLOv8:

from ultralytics import YOLO

# Load the default pre-trained YOLOv8 model
model = YOLO("yolov8n.pt")

# Run detection on an image
results = model(["image/car.jpg"])

# Iterate over the detection results
for result in results:
    boxes = result.boxes      # bounding boxes
    masks = result.masks      # segmentation masks, when supported by the model
    keypoints = result.keypoints  # pose keypoints
    probs = result.probs      # classification probabilities
    obb = result.obb          # oriented bounding boxes

    # Display the result
    result.show()

    # Save the result to a file
    result.save(filename="result.jpg")

How It Works

  • Load the modelYOLO("yolov8n.pt") loads the pre-trained YOLOv8 Nano model. If it is not available locally, Ultralytics downloads it automatically.
  • Detect objectsmodel(["image/car.jpg"]) runs inference on the image. Replace the path with any image you want to analyze.
  • Read the results → the result can contain bounding boxes, segmentation masks, pose keypoints, classification probabilities, and other task-specific output.
  • Output → display the annotated result with result.show() or save it with result.save().

Conclusion

With only a few lines of code, YOLOv8 can perform object detection quickly and conveniently. From here, you can experiment with batches of images or move on to real-time detection with a camera.

Related Posts

chevron-up