I’m using the Ultralytics YOLOv8 model for object detection on my custom dataset (which has two classes). After running predictions, I want to calculate and save the Intersection Over Union (IoU) for each detected bounding box alongside the confidence scores.
Here’s the relevant part of my code where I run the predictions:
from ultralytics import YOLO
import os
# Initialize the YOLO model with pre-trained weights
model = YOLO('runs/detect/yolov8n/weights/best.pt')
# Directory containing test images
images_directory = 'path_to_test_images_directory'
results_directory = 'path_to_save_predict_results_yolov8n'
os.makedirs(results_directory, exist_ok=True)
image_files = [os.path.join(images_directory, f) for f in os.listdir(images_directory) if f.endswith(('.jpg', '.png', '.jpeg'))]
for image_path in image_files:
results = model.predict(source=image_path, save_txt=True, save_conf=True, show_labels=True, show_conf=True)
print("All images have been processed and results saved.")
This is the one of the sample of predicted boxes on image.
0 0.75847 0.525917 0.48199 0.516998 0.976422
0 0.223181 0.527131 0.446362 0.516285 0.973426
1 0.487469 0.288411 0.0540745 0.0805167 0.836555
I am able to save the predictions and confidence scores but am unsure how to calculate and store the IoU for each prediction relative to the ground truth bounding boxes, which I have available in a separate dataset.
Questions:
- How can I modify my code to calculate the IoU for each predicted
bounding box against its corresponding ground truth? - What would be an efficient way to save these IoU scores
alongside the confidence scores for further analysis?
Any guidance or sample code would be greatly appreciated!