Utilizing YOLOv8 for Object Detection and Displaying Labels with Probabilities

1 min read .

We will explore how to use YOLOv8 to detect objects in an image and display the labels along with their probabilities. YOLO (You Only Look Once) is one of the most powerful object detection algorithms, and the latest version, YOLOv8, offers improved performance and advanced features.

Let’s walk through the practical steps to use the YOLOv8 model for object detection and display the detection results.

Prerequisites

Ensure that you have installed Python and the ultralytics library. If you haven’t installed it yet, you can do so using pip:

pip install ultralytics

Object Detection Code

Here is an example of Python code to load the YOLOv8 model and detect objects in an image:

from ultralytics import YOLO

# Load a model
model = YOLO("yolov8n.pt")  # pretrained YOLOv8n model

# Run batched inference on a list of images
results = model(["image/car.jpg"])  # return a list of Results objects

# Process results list
for result in results:
    for cls, prob, box in zip(result.boxes.cls, result.boxes.conf, result.boxes.xyxy):
        label = model.names[int(cls)]
        print(f"Detected label: {label} with probability: {prob:.2f}")

Code Explanation

  1. Loading the Model:

    • model = YOLO("yolov8n.pt") loads the pretrained YOLOv8 model. You need to ensure that the yolov8n.pt model file is in your working directory or download it from the YOLO repository.
  2. Running Inference:

    • results = model(["image/car.jpg"]) runs object detection on the specified image. You can replace "image/car.jpg" with the path to another image you want to process. The detection results are returned as a list of Results objects.
  3. Processing Detection Results:

    • Using zip(result.boxes.cls, result.boxes.conf, result.boxes.xyxy) to iterate over the detected object classes, probabilities, and bounding boxes.
    • model.names[int(cls)] is used to get the object class label based on the detected class ID.
    • print(f"Detected label: {label} with probability: {prob:.2f}") displays the detected object label along with its probability.

Conclusion

Using YOLOv8 with the ultralytics library allows you to efficiently perform object detection and display the results with labels and probabilities. This is particularly useful in applications requiring real-time object monitoring or image analysis. By following the example code above, you can easily integrate object detection into your application and obtain detailed information about the detected objects.

Tags:
AI

See Also

chevron-up