yolo txt format data transform to pascal voc format data with python
- User
yolo txt format data transform to pascal voc format data with python
- Assistant
- User
the yolo format data structure is images/train/val labels/train/val
- Assistant
yolo txt format data transform to pascal voc format data with python
the yolo format data structure is images/train/val labels/train/val
The YOLO format and PASCAL VOC format are two different ways of representing image annotations for object detection tasks. Converting between these formats can be useful for training models that require a specific annotation format.
YOLO Format: In the YOLO annotation format, each object within an image is represented by one line in a .txt file corresponding to the image. Each line contains:
<class_id> <x_center> <y_center> <width> <height>
Here, x_center, y_center, width, and height are normalized values relative to the dimensions of the image (ranging from 0 to 1).
PASCAL VOC Format: PASCAL VOC uses XML files for each image's annotations. An example of the structure is:
<annotation>
<folder>images</folder>
<filename>image1.jpg</filename>
<path>/path/to/image1.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>800</width>
<height>600</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>classname</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>50</xmin>
<ymin>50</ymin>
<xmax>200</xmax>
<ymax>200</ymax>
</bndbox>
</object>
</annotation>
To convert YOLO formatted data to PASCAL VOC, you'll need to:
Here is a Python script that demonstrates how to perform this conversion:
import os
import xml.etree.ElementTree as ET
from PIL import Image
def yolo_to_voc(yolo_txt_file, img_file, output_dir, class_mapping):
# Read image to get dimensions
img = Image.open(img_file)
img_width, img_height = img.size
# Prepare the XML file structure
annotation = ET.Element("annotation")
ET.SubElement(annotation, "folder").text = "images"
ET.SubElement(annotation, "filename").text = os.path.basename(img_file)
ET.SubElement(annotation, "path").text = img_file
ET.SubElement(annotation, "segmented").text = "0"
size = ET.SubElement(annotation, "size")
ET.SubElement(size, "width").text = str(img_width)
ET.SubElement(size, "height").text = str(img_height)
ET.SubElement(size, "depth").text = "3"
# Open the YOLO formatted annotation file
with open(yolo_txt_file, "r") as file:
for line in file:
class_id, x_center, y_center, width, height = map(float, line.split())
class_name = class_mapping[int(class_id)]
# Convert YOLO to VOC
x_center, y_center, width, height = (x_center * img_width, y_center * img_height,
width * img_width, height * img_height)
xmin = int(x_center - width / 2)
ymin = int(y_center - height / 2)
xmax = int(x_center + width / 2)
ymax = int(y_center + height / 2)
obj = ET.SubElement(annotation, "object")
ET.SubElement(obj, "name").text = class_name
ET.SubElement(obj, "pose").text = "Unspecified"
ET.SubElement(obj, "truncated").text = "0"
ET.SubElement(obj, "difficult").text = "0"
bndbox = ET.SubElement(obj, "bndbox")
ET.SubElement(bndbox, "xmin").text = str(xmin)
ET.SubElement(bndbox, "ymin").text = str(ymin)
ET.SubElement(bndbox, "xmax").text = str(xmax)
ET.SubElement(bndbox, "ymax").text = str(ymax)
# Write to XML file
tree = ET.ElementTree(annotation)
xml_file_name = os.path.join(output_dir, os.path.splitext(os.path.basename(img_file))[0] + ".xml")
tree.write(xml_file_name)
# Usage example
class_mapping = {0: "dog", 1: "cat"} # Define your class ID to name mapping
yolo_txt_file = "annotations.txt"
img_file = "image.jpg"
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
yolo_to_voc(yolo_txt_file, img_file, output_dir, class_mapping)
Make sure to adjust class_mapping to match the classes in your dataset. This script assumes the YOLO text file and the image file have names that allow them to be associated correctly. You might need to loop through multiple files and adjust paths according to your specific directory setup.
If you're working with a directory structure where images and their corresponding YOLO annotation files are segregated into training and validation sets such as:
- images
- train
- val
- labels
- train
- val
and you want to convert these annotations to the PASCAL VOC format following this kind of organized structure, you will need to adjust the script to handle multiple files and maintain the directory structure for output.
Here’s an extended version of the script to handle the structured data and ensure it properly processes each image and its corresponding annotation file from train and validation sets:
import os
import xml.etree.ElementTree as ET
from PIL import Image
def create_voc_xml(annotation, img_file, img_width, img_height, objects):
annotation = ET.Element("annotation")
ET.SubElement(annotation, "folder").text = os.path.split(os.path.dirname(img_file))[-1]
ET.SubElement(annotation, "filename").text = os.path.basename(img_file)
ET.SubElement(annotation, "path").text = img_file
ET.SubElement(annotation, "segmented").text = "0"
size = ET.SubElement(annotation, "size")
ET.SubElement(size, "width").text = str(img_width)
ET.SubElement(size, "height").text = str(img_height)
ET.SubElement(size, "depth").text = "3"
for obj in objects:
obj_elem = ET.SubElement(annotation, "object")
ET.SubElement(obj_elem, "name").text = obj["name"]
ET.SubElement(obj_elem, "pose").text = "Unspecified"
ET.SubElement(obj_elem, "truncated").text = "0"
ET.SubElement(obj_elem, "difficult").text = "0"
bndbox = ET.SubElement(obj_elem, "bndbox")
ET.SubElement(bndbox, "xmin").text = str(obj["xmin"])
ET.SubElement(bndbox, "ymin").text = str(obj["ymin"])
ET.SubElement(bndbox, "xmax").text = str(obj["xmax"])
ET.SubElement(bndbox, "ymax").text = str(obj["ymax"])
tree = ET.ElementTree(annotation)
xml_file_name = os.path.splitext(img_file)[0] + ".xml"
tree.write(xml_file_name)
def convert_yolo_to_voc(base_dir, class_mapping):
image_dirs = ["images/train", "images/val"]
label_dirs = ["labels/train", "labels/val"]
assert len(image_dirs) == len(label_dirs), "Image and label directory lists are mismatched in length."
for img_dir, lbl_dir in zip(image_dirs, label_dirs):
img_folder = os.path.join(base_dir, img_dir)
lbl_folder = os.path.join(base_dir, lbl_dir)
out_folder = os.path.join(base_dir, "Annotations", img_dir.split('/')[-1])
if not os.path.exists(out_folder):
os.makedirs(out_folder, exist_ok=True)
for img_filename in os.listdir(img_folder):
img_path = os.path.join(img_folder, img_filename)
lbl_path = os.path.join(lbl_folder, os.path.splitext(img_filename)[0] + ".txt")
if os.path.exists(lbl_path):
img = Image.open(img_path)
img_width, img_height = img.size
objects = []
with open(lbl_path, 'r') as file:
for line in file:
class_id, x_center, y_center, width, height = map(float, line.split())
class_name = class_mapping[int(class_id)]
x_center, y_center, width, height = (x_center * img_width, y_center * img_height,
width * img_width, height * img_height)
xmin = int(x_center - width / 2)
ymin = int(y_center - height / 2)
xmax = int(x_center + width / 2)
ymax = int(y_center + height / 2)
objects.append({
"name": class_name,
"xmin": xmin,
"ymin": ymin,
"xmax": xmax,
"ymax": ymax
})
create_voc_xml(annotation=None, img_file=img_path, img_width=img_width, img_height=img_height, objects=objects)
# Example Usage
class_mapping = {0: "dog", 1: "cat"} # Map your class IDs to class names
base_dir = "/path/to/dataset"
convert_yolo_to_voc(base_dir, class_mapping)
This expanded script loops over both the training and validation directories, reads images and their corresponding YOLO-formatted text files, and generates PASCAL VOC-formatted XML files in a new directory structure called "Annotations" nested under 'train' and 'val'. The function create_voc_xml centralizes the XML creation process, helping keep the conversion process modular and easier to manage. Update base_dir and class_mapping to fit your setup and dataset.
Not yet included in a published release.