To draw bounding boxes on images using YOLOv5 labels with a confidence threshold of 0.5, you can use the OpenCV library in Python. Below is a sample code that processes a set of YOLOv5 formatted labels and draws bounding boxes on the corresponding images. Make sure you have YOLOv5 label files, each containing information about the bounding boxes in the format: <class_id> <x_center> <y_center> <width> <height>, where these values are normalized between 0 and 1.
import cv2
import os
# Function to draw bounding boxes on an image
def draw_boxes(image_path, labels_path, output_path, threshold=0.5):
# Load image
image = cv2.imread(image_path)
height, width, _ = image.shape
# Read labels
with open(labels_path, 'r') as file:
lines = file.readlines()
for line in lines:
components = line.strip().split()
class_id, confidence, x_center, y_center, box_width, box_height = map(float, components)
if confidence < threshold:
continue
# YOLOv5 passes center of box, width and height. Convert to top left and bottom right points
x_center *= width
y_center *= height
box_width *= width
box_height *= height
x1 = int(x_center - (box_width / 2))
y1 = int(y_center - (box_height / 2))
x2 = int(x_center + (box_width / 2))
y2 = int(y_center + (box_height / 2))
# Draw bounding box on the image
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, f"Class: {int(class_id)} Confidence: {confidence:.2f}",
(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
# Save the newly created image
os.makedirs(os.path.dirname(output_path), exist_ok=True)
cv2.imwrite(output_path, image)
# Example usage
base_image_path = 'path/to/your/images'
base_labels_path = 'path/to/your/labels'
base_output_path = 'path/to/save/output_images'
# Loop through all your images and label files
for filename in os.listdir(base_labels_path):
if filename.endswith('.txt'): # YOLOv5 label files are usually .txt
image_name = os.path.splitext(filename)[0] + '.jpg' # Assuming your images are in jpg format
image_path = os.path.join(base_image_path, image_name)
labels_path = os.path.join(base_labels_path, filename)
output_path = os.path.join(base_output_path, image_name)
# Draw bounding boxes and save the image
draw_boxes(image_path, labels_path, output_path)
Notes:
- Make sure you replace
'path/to/your/images', 'path/to/your/labels', and 'path/to/save/output_images' with the correct paths to your images directory, labels directory, and desired output directory.
- The label files should be in YOLOv5 format with each line containing the class ID, confidence score, bounding box center coordinates, width, and height, all normalized between 0 and 1.
- Ensure that OpenCV is installed in your environment. You can install it via
pip install opencv-python-headless or just pip install opencv-python.