Using YOLOv8 for Object Detection with Labels and Confidence Scores
In this article, we will use YOLOv8 to detect objects in an image and print each object’s label and confidence score.
YOLO (You Only Look Once) has long been a popular choice for object detection, and YOLOv8 provides a convenient Python API through the ultralytics package.
Here is how to use it.
Prerequisites
Make sure Python and the ultralytics library are installed on your system. If needed, install the package with pip:
pip install ultralyticsObject Detection Example
The following example detects objects and prints their labels and confidence scores:
from ultralytics import YOLO
# Load the lightweight YOLOv8 Nano model
model = YOLO("yolov8n.pt")
# Run detection on an image
results = model(["image/car.jpg"])
# Process the detection results
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 object: {label} with confidence {prob:.2f}")How It Works
-
Load the model
YOLO("yolov8n.pt")loads the default YOLOv8 Nano model. If the model file is not available locally, it is downloaded automatically. -
Run image detection
model(["image/car.jpg"])performs inference on the image. Replace the path with another image as needed. -
Read the detection output
result.boxes.cls: object class IDs.result.boxes.conf: confidence scores.result.boxes.xyxy: bounding-box coordinates.model.names[int(cls)]: converts a class ID into its human-readable label.
-
Use the output This example prints labels and confidence scores to the terminal, but the same data can be used to draw annotations or feed another processing step.
Conclusion
A few lines of Python are enough to detect objects with YOLOv8 and inspect their labels and confidence scores. You can extend this example by drawing annotations directly on images or running detection in real time with a webcam.