Working with CVAT Bounding Box Annotations in Torchvision
- Introduction
- Getting Started with the Code
- Setting Up Your Python Environment
- Importing the Required Dependencies
- Loading and Exploring the Dataset
- Preparing the Data
- Conclusion
Introduction
Welcome to this hands-on guide for working with bounding box annotations created with the CVAT annotation tool in torchvision. Bounding box annotations specify rectangular frames around objects in images to identify and locate them for training object detection models.
The tutorial walks through setting up a Python environment, loading the raw annotations into a Pandas DataFrame, annotating and augmenting images using torchvision’s Transforms V2 API, and creating a custom Dataset class to feed samples to a model.
This guide is suitable for beginners and experienced practitioners, providing the code, explanations, and resources needed to understand and implement each step. By the end, you will have a solid foundation for working with bounding box annotations made with CVAT for object detection tasks.
Getting Started with the Code
The tutorial code is available as a Jupyter Notebook, which you can run locally or in a cloud-based environment like Google Colab. I have dedicated tutorials for those new to these platforms or who need guidance setting up:
Jupyter Notebook: | GitHub Repository | Open In Colab |
---|---|---|
Setting Up Your Python Environment
Before diving into the code, we’ll cover the steps to create a local Python environment and install the necessary dependencies.
Creating a Python Environment
First, we’ll create a Python environment using Conda/Mamba. Open a terminal with Conda/Mamba installed and run the following commands:
# Create a new Python 3.10 environment
conda create --name pytorch-env python=3.10 -y
# Activate the environment
conda activate pytorch-env
# Create a new Python 3.10 environment
mamba create --name pytorch-env python=3.10 -y
# Activate the environment
mamba activate pytorch-env
Installing PyTorch
Next, we’ll install PyTorch. Run the appropriate command for your hardware and operating system.
# Install PyTorch with CUDA
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
# MPS (Metal Performance Shaders) acceleration is available on MacOS 12.3+
pip install torch torchvision torchaudio
# Install PyTorch for CPU only
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
# Install PyTorch for CPU only
pip install torch torchvision torchaudio
Installing Additional Libraries
We also need to install some additional libraries for our project.
Package | Description |
---|---|
jupyter |
An open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. (link) |
matplotlib |
This package provides a comprehensive collection of visualization tools to create high-quality plots, charts, and graphs for data exploration and presentation. (link) |
pandas |
This package provides fast, powerful, and flexible data analysis and manipulation tools. (link) |
pillow |
The Python Imaging Library adds image processing capabilities. (link) |
tqdm |
A Python library that provides fast, extensible progress bars for loops and other iterable objects in Python. (link) |
distinctipy |
A lightweight python package providing functions to generate colours that are visually distinct from one another. (link) |
Run the following commands to install these additional libraries:
# Install additional dependencies
pip install distinctipy jupyter matplotlib pandas pillow tqdm
Installing Utility Packages
We will also install some utility packages I made, which provide shortcuts for routine tasks.
Package | Description |
---|---|
cjm_pil_utils |
Some PIL utility functions I frequently use. (link) |
cjm_psl_utils |
Some utility functions using the Python Standard Library. (link) |
cjm_pytorch_utils |
Some utility functions for working with PyTorch. (link) |
cjm_torchvision_tfms |
Some custom Torchvision tranforms. (link) |
Run the following commands to install the utility packages:
# Install additional utility packages
pip install cjm_pil_utils cjm_psl_utils cjm_pytorch_utils cjm_torchvision_tfms
With our environment set up, we can open our Jupyter Notebook and dive into the code.
Importing the Required Dependencies
First, we will import the necessary Python packages into our Jupyter Notebook.
# Import Python Standard Library dependencies
from functools import partial
from pathlib import Path
import xml.etree.ElementTree as ET
# Import utility functions
from cjm_pil_utils.core import get_img_files
from cjm_psl_utils.core import download_file, file_extract
from cjm_pytorch_utils.core import tensor_to_pil
from cjm_torchvision_tfms.core import ResizeMax, PadSquare, CustomRandomIoUCrop
# Import the distinctipy module
from distinctipy import distinctipy
# Import matplotlib for creating plots
import matplotlib.pyplot as plt
# Import numpy
import numpy as np
# Import the pandas package
import pandas as pd
# Do not truncate the contents of cells and display all rows and columns
'max_colwidth', None, 'display.max_rows', None, 'display.max_columns', None)
pd.set_option(
# Import PIL for image manipulation
from PIL import Image
# Import PyTorch dependencies
import torch
from torch.utils.data import Dataset, DataLoader
# Import torchvision dependencies
import torchvision
torchvision.disable_beta_transforms_warning()from torchvision.tv_tensors import BoundingBoxes
from torchvision.utils import draw_bounding_boxes
import torchvision.transforms.v2 as transforms
# Import tqdm for progress bar
from tqdm.auto import tqdm
Torchvision provides dedicated torch.Tensor
subclasses for different annotation types called TVTensors
. Torchvision’s V2 transforms use these subclasses to update the annotations based on the applied image augmentations. The TVTensor class for bounding box annotations is called BoundingBoxes
. Torchvision also includes a draw_bounding_boxes
function to annotate images.
Loading and Exploring the Dataset
After importing the dependencies, we can start working with our data. I annotated a toy dataset with bounding boxes for this tutorial using images from the free stock photo site Pexels. The dataset is available on HuggingFace Hub at the link below:
- Dataset Repository: cvat-bounding-box-toy-dataset
Setting the Directory Paths
We first need to specify a place to store our dataset and a location to download the zip file containing it. The following code creates the folders in the current directory (./
). Update the path if that is not suitable for you.
# Define path to store datasets
= Path("./Datasets/")
dataset_dir # Create the dataset directory if it does not exist
=True, exist_ok=True)
dataset_dir.mkdir(parents
# Define path to store archive files
= dataset_dir/'../Archive'
archive_dir # Create the archive directory if it does not exist
=True, exist_ok=True)
archive_dir.mkdir(parents
# Creating a Series with the paths and converting it to a DataFrame for display
pd.Series({"Dataset Directory:": dataset_dir,
"Archive Directory:": archive_dir
='columns') }).to_frame().style.hide(axis
Dataset Directory: | Datasets |
---|---|
Archive Directory: | Datasets/../Archive |
Setting the Dataset Path
Next, we construct the name for the Hugging Face Hub dataset and set where to download and extract the dataset.
# Set the name of the dataset
= 'cvat-bounding-box-toy-dataset'
dataset_name
# Construct the HuggingFace Hub dataset name by combining the username and dataset name
= f'cj-mills/{dataset_name}'
hf_dataset
# Create the path to the zip file that contains the dataset
= Path(f'{archive_dir}/{dataset_name}.zip')
archive_path
# Create the path to the directory where the dataset will be extracted
= Path(f'{dataset_dir}/{dataset_name}')
dataset_path
# Creating a Series with the dataset name and paths and converting it to a DataFrame for display
pd.Series({"HuggingFace Dataset:": hf_dataset,
"Archive Path:": archive_path,
"Dataset Path:": dataset_path
='columns') }).to_frame().style.hide(axis
HuggingFace Dataset: | cj-mills/cvat-bounding-box-toy-dataset |
---|---|
Archive Path: | Datasets/../Archive/cvat-bounding-box-toy-dataset.zip |
Dataset Path: | Datasets/cvat-bounding-box-toy-dataset |
Downloading the Dataset
We can now download the archive file and extract the dataset using the download_file
and file_extract
functions from the cjm_psl_utils
package. We can delete the archive afterward to save space.
# Construct the HuggingFace Hub dataset URL
= f"https://huggingface.co/datasets/{hf_dataset}/resolve/main/{dataset_name}.zip"
dataset_url print(f"HuggingFace Dataset URL: {dataset_url}")
# Set whether to delete the archive file after extracting the dataset
= True
delete_archive
# Download the dataset if not present
if dataset_path.is_dir():
print("Dataset folder already exists")
else:
print("Downloading dataset...")
download_file(dataset_url, archive_dir)
print("Extracting dataset...")
=archive_path, dest=dataset_dir)
file_extract(fname
# Delete the archive if specified
if delete_archive: archive_path.unlink()
Getting the Images and Annotations
The dataset has a folder containing the sample images and an XML file containing the annotations.
# Assuming the images are stored in a subfolder named 'default'
= dataset_path/'images/default'
img_dir
# Assuming annotation file is in XML format and located in any subdirectory of the dataset
= dataset_path/'annotations.xml'
annotation_file_path
# Creating a Series with the paths and converting it to a DataFrame for display
pd.Series({"Image Folder": img_dir,
"Annotation File": annotation_file_path}).to_frame().style.hide(axis='columns')
Image Folder | Datasets/cvat-bounding-box-toy-dataset/images/default |
---|---|
Annotation File | Datasets/cvat-bounding-box-toy-dataset/annotations.xml |
Get Image File Paths
Each image file has a unique name that we can use to locate the corresponding annotation data. We can make a dictionary that maps image names to file paths. The dictionary will allow us to retrieve the file path for a given image more efficiently.
# Get all image files in the 'img_dir' directory
= {
img_dict file.stem : file # Create a dictionary that maps file names to file paths
for file in get_img_files(img_dir) # Get a list of image files in the image directory
}
# Print the number of image files
print(f"Number of Images: {len(img_dict)}")
# Display the first five entries from the dictionary using a Pandas DataFrame
='index').head() pd.DataFrame.from_dict(img_dict, orient
Number of Images: 28
0 | |
---|---|
258421 | Datasets/cvat-bounding-box-toy-dataset/images/default/258421.jpg |
3075367 | Datasets/cvat-bounding-box-toy-dataset/images/default/3075367.jpg |
3076319 | Datasets/cvat-bounding-box-toy-dataset/images/default/3076319.jpg |
3145551 | Datasets/cvat-bounding-box-toy-dataset/images/default/3145551.jpg |
3176048 | Datasets/cvat-bounding-box-toy-dataset/images/default/3176048.jpg |
Get Image Annotations
Next, we read the content of the XML annotation file into a Pandas DataFrame so we can easily query the annotations.
Define a function to parse the CVAT XML annotations
The following helper function parses the raw XML content into a Pandas DataFrame.
def parse_cvat_bbox_xml(xml_content):
"""
Parse the given XML content of a CVAT bounding box annotation file and
convert it into a pandas DataFrame.
This function processes the XML content to extract information about each
image and its associated bounding boxes. The data is then structured into
a DataFrame for easier manipulation and analysis.
Parameters:
xml_content (str): A string containing the XML content from a CVAT bounding box
annotation file.
Returns:
pandas.DataFrame: A DataFrame where each row represents an image and contains
the following columns:
- Image ID (int): The unique identifier of the image.
- Image Name (str): The name of the image.
- Width (int): The width of the image in pixels.
- Height (int): The height of the image in pixels.
- Boxes (list): A list of dictionaries, where each dictionary
represents a bounding box with keys 'Label',
'xtl', 'ytl', 'xbr', and 'ybr' indicating the
label and coordinates of the box.
"""
# Parse the XML content
= ET.fromstring(xml_content)
root = {}
data
# Iterate through each image element in the XML
for image in root.findall('image'):
# Extract image attributes
= image.get('id')
image_id = image.get('name')
image_name = image.get('width')
width = image.get('height')
height
# Initialize a dictionary to store image data
= {
image_data 'Image ID': int(image_id),
'Image Name': image_name,
'Width': int(width),
'Height': int(height),
'Boxes': []
}
# Iterate through each bounding box element within the image
for box in image.findall('box'):
# Extract box attributes
= box.get('label')
label = float(box.get('xtl'))
xtl = float(box.get('ytl'))
ytl = float(box.get('xbr'))
xbr = float(box.get('ybr'))
ybr
# Construct a dictionary for the box data
= {
box_data 'Label': label,
'xtl': xtl,
'ytl': ytl,
'xbr': xbr,
'ybr': ybr
}
# Append the box data to the image's 'Boxes' list
'Boxes'].append(box_data)
image_data[
# Map the image data to its ID in the data dictionary
= image_data
data[image_id]
# Convert the data dictionary to a DataFrame and return
return pd.DataFrame.from_dict(data, orient='index')
Load CVAT XML annotations into a DataFrame
After parsing the XML content, we will change the index for the annotation_df
DataFrame to match the keys in the img_dict
dictionary, allowing us to retrieve both the image paths and annotation data using the same index key.
# Read the XML file
with open(annotation_file_path, 'r', encoding='utf-8') as file:
= file.read()
xml_content
# Parse the XML content
= parse_cvat_bbox_xml(xml_content)
annotation_df
# Add a new column 'Image ID' by extracting it from 'Image Name'
# This assumes that the 'Image ID' is the part of the 'Image Name' before the first period
'Image ID'] = annotation_df['Image Name'].apply(lambda x: x.split('.')[0])
annotation_df[
# Set the new 'Image ID' column as the index of the DataFrame
= annotation_df.set_index('Image ID')
annotation_df
# Display the first few rows of the DataFrame
annotation_df.head()
Image Name | Width | Height | Boxes | |
---|---|---|---|---|
Image ID | ||||
258421 | 258421.jpg | 768 | 1152 | [{‘Label’: ‘person’, ‘xtl’: 386.08, ‘ytl’: 443.94, ‘xbr’: 460.82, ‘ybr’: 777.16}, {‘Label’: ‘person’, ‘xtl’: 340.25, ‘ytl’: 466.94, ‘xbr’: 418.99, ‘ybr’: 777.34}] |
3075367 | 3075367.jpg | 1344 | 768 | [{‘Label’: ‘person’, ‘xtl’: 413.32, ‘ytl’: 41.22, ‘xbr’: 919.81, ‘ybr’: 763.17}] |
3076319 | 3076319.jpg | 768 | 1120 | [{‘Label’: ‘person’, ‘xtl’: 335.31, ‘ytl’: 151.75, ‘xbr’: 711.22, ‘ybr’: 1117.49}, {‘Label’: ‘person’, ‘xtl’: 8.11, ‘ytl’: 131.88, ‘xbr’: 404.2, ‘ybr’: 1119.0}] |
3145551 | 3145551.jpg | 1184 | 768 | [{‘Label’: ‘person’, ‘xtl’: 642.0, ‘ytl’: 289.85, ‘xbr’: 669.66, ‘ybr’: 398.89}, {‘Label’: ‘person’, ‘xtl’: 658.63, ‘ytl’: 281.25, ‘xbr’: 687.09, ‘ybr’: 398.61}] |
3176048 | 3176048.jpg | 1152 | 768 | [{‘Label’: ‘person’, ‘xtl’: 518.23, ‘ytl’: 338.97, ‘xbr’: 594.63, ‘ybr’: 466.08}, {‘Label’: ‘person’, ‘xtl’: 683.42, ‘ytl’: 356.48, ‘xbr’: 638.86, ‘ybr’: 437.82}] |
The source XML content corresponding to the first row in the DataFrame is available below:
<?xml version="1.0" encoding="utf-8"?>
annotations>
<version>1.1</version>
<meta>
<meta>
</image id="0" name="258421.jpg" subset="default" task_id="7" width="768" height="1152">
<box label="person" source="file" occluded="0" xtl="386.08" ytl="443.94" xbr="460.82" ybr="777.16" z_order="0">
<box>
</box label="person" source="file" occluded="0" xtl="340.25" ytl="466.94" xbr="418.99" ybr="777.34" z_order="0">
<box>
</image>
</annotations> </
The the xtl
, ytl
, xbr
, and ybr
values indicate the bounding box annotations are in [Top-Left X, Top-Left Y, Bottom-Right X, Bottom-Right Y]
format.
With the annotations loaded, we can start inspecting our dataset.
Inspecting the Class Distribution
First, we get the names of all the classes in our dataset and inspect the distribution of samples among these classes. This step won’t yield any insights for the toy dataset but is worth doing for real-world projects. A balanced dataset (where each class has approximately the same number of instances) is ideal for training a machine-learning model.
Get image classes
# Explode the 'boxes_df' column in the annotation_df dataframe
# Convert the resulting series to a dataframe and rename the 'boxes_df' column to 'boxes_df'
# Apply the pandas Series function to the 'boxes_df' column of the dataframe
= annotation_df['Boxes'].explode().to_frame().Boxes.apply(pd.Series)
boxes_df
# Get a list of unique labels in the 'annotation_df' DataFrame
= boxes_df['Label'].unique().tolist()
class_names
# Display labels using a Pandas DataFrame
pd.DataFrame(class_names)
0 | |
---|---|
0 | person |
Visualize the class distribution
# Get the number of samples for each object class
= boxes_df['Label'].value_counts()
class_counts
# Plot the distribution
='bar', figsize=(12, 5))
class_counts.plot(kind'Class distribution')
plt.title('Count')
plt.ylabel('Classes')
plt.xlabel(range(len(class_counts.index)), class_counts.index, rotation=75) # Set the x-axis tick labels
plt.xticks( plt.show()
Visualizing Image Annotations
In this section, we will annotate a single image with its bounding boxes using torchvision’s BoundingBoxes
class and draw_bounding_boxes
function.
Generate a color map
While not required, assigning a unique color to bounding boxes for each object class enhances visual distinction, allowing for easier identification of different objects in the scene. We can use the distinctipy
package to generate a visually distinct colormap.
# Generate a list of colors with a length equal to the number of labels
= distinctipy.get_colors(len(class_names))
colors
# Make a copy of the color map in integer format
= [tuple(int(c*255) for c in color) for color in colors]
int_colors
# Generate a color swatch to visualize the color map
distinctipy.color_swatch(colors)
Download a font file
The draw_bounding_boxes
function included with torchvision uses a pretty small font size. We can increase the font size if we use a custom font. Font files are available on sites like Google Fonts, or we can use one included with the operating system.
# Set the name of the font file
= 'KFOlCnqEu92Fr1MmEU9vAw.ttf'
font_file
# Download the font file
f"https://fonts.gstatic.com/s/roboto/v30/{font_file}", "./") download_file(
Define the bounding box annotation function
We can make a partial function using draw_bounding_boxes
since we’ll use the same box thickness and font each time we visualize bounding boxes.
= partial(draw_bounding_boxes, fill=False, width=2, font=font_file, font_size=25) draw_bboxes
Selecting a Sample Image
We can use the unique ID for an image in the image dictionary to get the image file path and the associated annotations from the annotation DataFrame.
Load the sample image
# Get the file ID of the first image file
= list(img_dict.keys())[0]
file_id
# Open the associated image file as a RGB image
= Image.open(img_dict[file_id]).convert('RGB')
sample_img
# Print the dimensions of the image
print(f"Image Dims: {sample_img.size}")
# Show the image
sample_img
Image Dims: (768, 1152)
Inspect the corresponding annotation data
# Get the row from the 'annotation_df' DataFrame corresponding to the 'file_id'
annotation_df.loc[file_id].to_frame()
258421 | |
---|---|
Image Name | 258421.jpg |
Width | 768 |
Height | 1152 |
Boxes | [{‘Label’: ‘person’, ‘xtl’: 386.08, ‘ytl’: 443.94, ‘xbr’: 460.82, ‘ybr’: 777.16}, {‘Label’: ‘person’, ‘xtl’: 340.25, ‘ytl’: 466.94, ‘xbr’: 418.99, ‘ybr’: 777.34}] |
Annotate sample image
The draw_bounding_boxes
function expects bounding box annotations in [top-left X, top-left Y, bottom-right X, bottom-right Y]
format, so we don’t need to convert the annotation values.
# Extract the labels and bounding box annotations for the sample image
= [box['Label'] for box in annotation_df.loc[file_id]['Boxes']]
labels = np.array([[box['xtl'], box['ytl'], box['xbr'], box['ybr']] for box in annotation_df.loc[file_id]['Boxes']]).reshape(len(labels),4)
bboxes
# Annotate the sample image with labels and bounding boxes
= draw_bboxes(
annotated_tensor =transforms.PILToTensor()(sample_img),
image=BoundingBoxes(torch.Tensor(bboxes), format='xyxy', canvas_size=sample_img.size[::-1]),
boxes=labels,
labels=[int_colors[i] for i in [class_names.index(label) for label in labels]]
colors
)
tensor_to_pil(annotated_tensor)
We have loaded the dataset, inspected its class distribution, and visualized the annotations for a sample image. In the final section, we will cover how to augment images using torchvision’s Transforms V2 API and create a custom Dataset class for training.
Preparing the Data
In this section, we will first walk through a single example of how to apply augmentations to a single annotated image using torchvision’s Transforms V2 API before putting everything together in a custom Dataset class.
Data Augmentation
Here, we will define some data augmentations to apply to images during training. I created a few custom image transforms to help streamline the code.
The first extends the RandomIoUCrop
transform included with torchvision to give the user more control over how much it crops into bounding box areas. The second resizes images based on their largest dimension rather than their smallest. The third applies square padding and allows the padding to be applied equally on both sides or randomly split between the two sides.
All three are available through the cjm-torchvision-tfms
package.
Set training image size
Next, we will specify the image size to use during training.
# Set training image size
= 384 train_sz
Initialize custom transforms
Now, we can initialize the transform objects.
# Create a RandomIoUCrop object
= CustomRandomIoUCrop(min_scale=0.3,
iou_crop =1.0,
max_scale=0.5,
min_aspect_ratio=2.0,
max_aspect_ratio=[0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0],
sampler_options=400,
trials=0.25)
jitter_factor
# Create a `ResizeMax` object
= ResizeMax(max_sz=train_sz)
resize_max
# Create a `PadSquare` object
= PadSquare(shift=True) pad_square
Test the transforms
Torchvision’s V2 image transforms take an image and a targets
dictionary. The targets
dictionary contains the annotations and labels for the image.
We will pass input through the CustomRandomIoUCrop
transform first and then through ResizeMax
and PadSquare
. We can pass the result through a final resize operation to ensure both sides match the train_sz
value.
# Prepare bounding box targets
= {
targets 'boxes': BoundingBoxes(torch.Tensor(bboxes),
format='xyxy',
=sample_img.size[::-1]),
canvas_size'labels': torch.Tensor([class_names.index(label) for label in labels])
}
# Crop the image
= iou_crop(sample_img, targets)
cropped_img, targets
# Resize the image
= resize_max(cropped_img, targets)
resized_img, targets
# Pad the image
= pad_square(resized_img, targets)
padded_img, targets
# Ensure the padded image is the target size
= transforms.Resize([train_sz] * 2, antialias=True)
resize = resize(padded_img, targets)
resized_padded_img, targets = transforms.SanitizeBoundingBoxes()(resized_padded_img, targets)
sanitized_img, targets
# Annotate the augmented image with updated labels and bounding boxes
= draw_bboxes(
annotated_tensor =transforms.PILToTensor()(sanitized_img),
image=targets['boxes'],
boxes=[class_names[int(label.item())] for label in targets['labels']],
labels=[int_colors[i] for i in [class_names.index(label) for label in labels]]
colors
)
# Display the annotated image
display(tensor_to_pil(annotated_tensor))
pd.Series({"Source Image:": sample_img.size,
"Cropped Image:": cropped_img.size,
"Resized Image:": resized_img.size,
"Padded Image:": padded_img.size,
"Resized Padded Image:": resized_padded_img.size,
='columns') }).to_frame().style.hide(axis
Source Image: | (768, 1152) |
---|---|
Cropped Image: | (768, 1152) |
Resized Image: | (256, 384) |
Padded Image: | (384, 384) |
Resized Padded Image: | (384, 384) |
Now that we know how to apply data augmentations, we can put all the steps we’ve covered into a custom Dataset class.
Training Dataset Class
The following custom Dataset class is responsible for loading a single image, preparing the associated annotations, applying any image transforms, and returning the final image
tensor and its target
dictionary during training.
class CVATBBoxDataset(Dataset):
"""
A custom dataset class for handling bounding box annotations from CVAT.
This dataset class is designed to work with bounding box annotations exported
from the CVAT annotation tool. It allows for loading images and their corresponding
bounding box annotations for use in training machine learning models.
Attributes:
_img_keys (list): A list of image keys.
_annotation_df (pandas.DataFrame): A DataFrame containing annotations.
_img_dict (dict): A dictionary mapping image keys to image file paths.
_class_to_idx (dict): A dictionary mapping class names to class indices.
_transforms (callable, optional): A function/transform that takes in an image
and a target, and returns a transformed version.
Args:
img_keys (list): List of image keys.
annotation_df (pandas.DataFrame): DataFrame containing annotations.
img_dict (dict): Dictionary mapping image keys to image paths.
class_to_idx (dict): Dictionary mapping class names to class indices.
transforms (callable, optional): Optional transform to be applied on a sample.
"""
def __init__(self, img_keys, annotation_df, img_dict, class_to_idx, transforms=None):
super(Dataset, self).__init__()
self._img_keys = img_keys
self._annotation_df = annotation_df
self._img_dict = img_dict
self._class_to_idx = class_to_idx
self._transforms = transforms
def __len__(self):
"""
Returns the total number of items in the dataset.
Returns:
int: Total number of items.
"""
return len(self._img_keys)
def __getitem__(self, index):
"""
Retrieves an image and its associated target (bounding boxes and labels) at the specified index.
Args:
index (int): The index of the item.
Returns:
tuple: A tuple containing an image and its corresponding target.
"""
= self._img_keys[index]
img_key = self._annotation_df.loc[img_key]
annotation = self._load_image_and_target(annotation)
image, target
if self._transforms:
= self._transforms(image, target)
image, target
return image, target
def _load_image_and_target(self, annotation):
"""
Loads an image and its corresponding target data (bounding boxes and labels) based on the provided annotation.
Args:
annotation (pandas.Series): The annotation data for a specific image.
Returns:
tuple: A tuple containing the image and a dictionary with 'boxes' and 'labels'.
"""
# Retrieve the file path from the image dictionary using the annotation's name as the key.
= self._img_dict[annotation.name]
filepath
# Open the image file and convert it to RGB.
= Image.open(filepath).convert('RGB')
image
# Extract bounding box coordinates from the annotation and convert them to a numpy array.
= np.array([[box['xtl'], box['ytl'], box['xbr'], box['ybr']] for box in annotation['Boxes']]).reshape(len(annotation['Boxes']), 4)
bbox_list
# Convert the numpy array of bounding boxes to a PyTorch tensor.
= torch.Tensor(bbox_list)
bbox_tensor
# Create bounding box objects with the tensor, specifying the format and canvas size.
= BoundingBoxes(bbox_tensor, format='xyxy', canvas_size=image.size[::-1])
boxes
# Extract labels from the annotation and map them to their corresponding indices.
= [box['Label'] for box in annotation['Boxes']]
annotation_labels = torch.Tensor([self._class_to_idx[label] for label in annotation_labels])
labels
# Return the image and a dictionary containing the bounding boxes and labels.
return image, {'boxes': boxes, 'labels': labels}
Image Transforms
Here, we will specify and organize all the image transforms to apply during training.
# Compose transforms for data augmentation
= transforms.Compose(
data_aug_tfms =[
transforms
iou_crop,
transforms.ColorJitter(= (0.875, 1.125),
brightness = (0.5, 1.5),
contrast = (0.5, 1.5),
saturation = (-0.05, 0.05),
hue
),
transforms.RandomGrayscale(),
transforms.RandomEqualize(),=3, p=0.5),
transforms.RandomPosterize(bits=0.5),
transforms.RandomHorizontalFlip(p
],
)
# Compose transforms to resize and pad input images
= transforms.Compose([
resize_pad_tfm
resize_max,
pad_square,* 2, antialias=True)
transforms.Resize([train_sz]
])
# Compose transforms to sanitize bounding boxes and normalize input data
= transforms.Compose([
final_tfms
transforms.ToImage(), =True),
transforms.ToDtype(torch.float32, scale
transforms.SanitizeBoundingBoxes(),
])
# Define the transformations for training and validation datasets
= transforms.Compose([
train_tfms
data_aug_tfms,
resize_pad_tfm,
final_tfms ])
Always use the SanitizeBoundingBoxes
transform to clean up annotations after using data augmentations that alter bounding boxes (e.g., cropping, warping, etc.).
Initialize Dataset
Now, we can create the dataset object using the image dictionary, the annotation DataFrame, and the image transforms.
# Create a mapping from class names to class indices
= {c: i for i, c in enumerate(class_names)}
class_to_idx
# Instantiate the dataset using the defined transformations
= CVATBBoxDataset(list(img_dict.keys()), annotation_df, img_dict, class_to_idx, train_tfms)
train_dataset
# Print the number of samples in the training dataset
pd.Series({'Training dataset size:': len(train_dataset),
='columns') }).to_frame().style.hide(axis
Training dataset size: | 28 |
---|
Inspect Samples
To close out, we should verify the dataset object works as intended by inspecting the first sample.
Inspect training set sample
= train_dataset[0]
dataset_sample
= draw_bboxes(
annotated_tensor =(dataset_sample[0]*255).to(dtype=torch.uint8),
image=dataset_sample[1]['boxes'],
boxes=[class_names[int(i.item())] for i in dataset_sample[1]['labels']],
labels=[int_colors[int(i.item())] for i in dataset_sample[1]['labels']]
colors
)
tensor_to_pil(annotated_tensor)
Conclusion
In this tutorial, we covered how to load custom bounding box annotations made with the CVAT annotation tool and work with them using torchvision’s Transforms V2 API. The skills and knowledge you acquired here provide a solid foundation for future object detection projects.
As a next step, perhaps try annotating a custom object detection dataset with CVAT and loading it with this tutorial’s code. Once you’re comfortable with that, try adapting the code in the following tutorial to train an object detection model on your custom dataset.
Recommended Tutorials
- Working with CVAT Keypoint Annotations in Torchvision: Learn how to work with CVAT keypoint annotations in torchvision for keypoint estimation tasks.
- Working with CVAT Segmentation Annotations in Torchvision: Learn how to work with CVAT segmentation annotations in torchvision for instance segmentation tasks.
- Training YOLOX Models for Real-Time Object Detection in PyTorch: Learn how to train YOLOX models for real-time object detection in PyTorch by creating a hand gesture detection model.
- Feel free to post questions or problems related to this tutorial in the comments below. I try to make time to address them on Thursdays and Fridays.
I’m Christian Mills, a deep learning consultant specializing in practical AI implementations. I help clients leverage cutting-edge AI technologies to solve real-world problems.
Interested in working together? Fill out my Quick AI Project Assessment form or learn more about me.