Object Detection with YOLOv8: A Guide to Using Pretrained Models on Images
We will explore how to use the YOLOv8 model for object detection on images. YOLO (You Only Look Once) is one of the most popular object detection algorithms, and YOLOv8 is the latest version that offers improved performance and accuracy. We will utilize the ultralytics
library to run object detection on images and process the detection results.
Prerequisites
Make sure you have:
- Python
- The
ultralytics
library
If you haven’t installed ultralytics
, you can do so with pip:
pip install ultralytics
Object Detection Code
Here is an example of Python code that uses YOLOv8 to 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:
boxes = result.boxes # Boxes object for bounding box outputs
masks = result.masks # Masks object for segmentation masks outputs
keypoints = result.keypoints # Keypoints object for pose outputs
probs = result.probs # Probs object for classification outputs
obb = result.obb # Oriented boxes object for OBB outputs
result.show() # display to screen
result.save(filename="result.jpg") # save to disk
Code Explanation
-
Loading the Model:
model = YOLO("yolov8n.pt")
loads the trained YOLOv8 model. Ensure theyolov8n.pt
model file is available in your working directory or download it from the YOLO repository.
-
Running Inference:
results = model(["image/car.jpg"])
runs object detection on the image. You can replace"image/car.jpg"
with the path to another image you want to process. The model will return a list of detection results.
-
Processing Detection Results:
boxes = result.boxes
accesses the bounding boxes from the detection results.masks = result.masks
retrieves segmentation masks if your model supports segmentation.keypoints = result.keypoints
accesses keypoints if you’re performing pose detection.probs = result.probs
stores the classification probabilities of the objects.obb = result.obb
accesses oriented boxes if used.
-
Displaying and Saving Results:
result.show()
displays the image annotated with object detections on the screen.result.save(filename="result.jpg")
saves the detection results image to disk with the filenameresult.jpg
.
Conclusion
By using YOLOv8 and the ultralytics
library, you can easily perform object detection on images and process the results. YOLOv8 offers high accuracy and fast detection speed, making it ideal for applications requiring real-time or batch object detection. This code can be further developed to handle various input types and customize the detection results to suit your needs.