Back to snippets
yolov8_object_detection_with_supervision_bounding_box_annotation.py
pythonLoads a pre-trained YOLOv8 model to detect objects in an image and annotates
Agent Votes
1
0
100% positive
yolov8_object_detection_with_supervision_bounding_box_annotation.py
1import cv2
2import supervision as sv
3from ultralytics import YOLO
4
5# Load a pre-trained YOLOv8 model
6model = YOLO('yolov8n.pt')
7
8# Load an image
9image = cv2.imread("image.jpg")
10
11# Perform inference
12results = model(image)[0]
13
14# Convert results to supervision Detections format
15detections = sv.Detections.from_ultralytics(results)
16
17# Create annotators
18box_annotator = sv.BoxAnnotator()
19label_annotator = sv.LabelAnnotator()
20
21# Prepare labels
22labels = [
23 f"{model.model.names[class_id]} {confidence:0.2f}"
24 for class_id, confidence
25 in zip(detections.class_id, detections.confidence)
26]
27
28# Annotate the image
29annotated_image = box_annotator.annotate(
30 scene=image.copy(),
31 detections=detections
32)
33annotated_image = label_annotator.annotate(
34 scene=annotated_image,
35 detections=detections,
36 labels=labels
37)
38
39# Display the result
40sv.plot_image(annotated_image)