【数据集映射】(含完整可行Python代码)Yolo格式数据(txt)转RCNN格式数据(coco)

1:需求背景

目标检测研究中,通常不同的模型需要不同的数据格式,如yolo需要txt、rcnn需要coco等,因此就需要对标注的数据格式进行转换。

通常的数据格式有txt、coco(json)、Pascal VOC、xml等。

本文的需求是txt转coco,下面提供一种可行的代码(可完全复制)

2:格式转换代码

需要修改的内容是:

1:图像和txt数据集的路径。这个是自己配制的,一般在dataset里面。将图像路径赋给images_dir,txt路径赋给annotations_dir即可。

# 路径配置(根据自己的路径修改)
images_dir = ""
annotations_dir = ""

2:categories内的映射字典。详情可以打开自己的txt文件,查看每一类对应的class_number,例如我们这里的yolo格式中的GD图像分类编号对应0,则映射字典出设置为【0: "xxx",】,其他内容同理。

# 类别映射字典(根据自己的内容修改)
categories = {
    0: "xxx",
}

# 后面可以加1、2、3...

3:数据集图像的大小参数。在以下位置处的【image_width】和【image_height】替换为自己图像的分辨率。

# TODO: 如果每张图片的大小都一样,你可以在这里指定
        # 如果大小不一样,你需要读取图片文件来获取实际尺寸
        image_width = 960
        image_height = 960

4:json文件的保存位置。在以下位置处的路径【'xxx.json'】修改为自己的想要存放的绝对路径/相对路径即可。

# 将COCO数据结构写入JSON文件(保存的json路径自己修改)
with open('xxx.json', 'w') as json_file:
    json.dump(coco_output, json_file, indent=4)

完整代码如下: 

import json
import os

# 路径配置(根据自己的路径修改)
images_dir = '/home/ubuntu/datasets'
annotations_dir = '/home/ubuntu/datasets'

# 类别映射字典(根据自己的内容修改)
categories = {
    0: "xxx",
}

# COCO格式的基本结构
coco_output = {
    "info": {},
    "licenses": [],
    "images": [],
    "annotations": [],
    "categories": [{"id": k, "name": v, "supercategory": ""} for k, v in categories.items()]
}

# 图片和标注的ID计数器
image_id = 1
annotation_id = 1

# 遍历annotations目录下的所有TXT文件
for filename in os.listdir(annotations_dir):
    if filename.endswith('.txt'):
        # 假设文件名与图片文件名一致(不包含扩展名)
        image_filename = filename.replace('.txt', '.jpg')
        image_path = os.path.join(images_dir, image_filename)
        
        # TODO: 如果每张图片的大小都一样,你可以在这里指定
        # 如果大小不一样,你需要读取图片文件来获取实际尺寸
        image_width = 960
        image_height = 960
        
        # 添加图片信息到COCO数据结构
        coco_output['images'].append({
            "id": image_id,
            "file_name": image_filename,
            "width": image_width,
            "height": image_height
        })
        
        # 读取每个TXT文件并添加标注信息
        txt_file_path = os.path.join(annotations_dir, filename)
        with open(txt_file_path, 'r') as file:
            for line in file:
                class_id, x_center, y_center, width, height = map(float, line.strip().split())
                
                # COCO要求bbox是[x_min, y_min, width, height],而不是中心点坐标
                x_min = (x_center - width / 2) * image_width
                y_min = (y_center - height / 2) * image_height
                width = width * image_width
                height = height * image_height
                
                # 添加标注信息
                coco_output['annotations'].append({
                    "id": annotation_id,
                    "image_id": image_id,
                    "category_id": class_id,
                    "bbox": [x_min, y_min, width, height],
                    "area": width * height,
                    "segmentation": [],  # 如果你有分割信息可以在这里添加
                    "iscrowd": 0
                })
                
                annotation_id += 1
        
        # 更新图片ID
        image_id += 1

# 将COCO数据结构写入JSON文件(保存的json路径自己修改)
with open('xxx.json', 'w') as json_file:
    json.dump(coco_output, json_file, indent=4)

print("Conversion completed!")

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是将YOLO格式数据集换为VOC格式数据集Python代码示例: ```python import os import xml.etree.ElementTree as ET # Define the classes present in your dataset classes = ["class1", "class2", "class3"] def convert_yolo_to_voc(yolo_path, voc_path): """ Convert YOLO format dataset to VOC format dataset :param yolo_path: path to the YOLO dataset directory :param voc_path: path to the VOC dataset directory """ # Create the VOC dataset directory if it doesn't exist if not os.path.exists(voc_path): os.makedirs(voc_path) # Loop through all the files in the YOLO dataset directory for file_name in os.listdir(yolo_path): if file_name.endswith(".txt"): # Open the YOLO annotation file with open(os.path.join(yolo_path, file_name), "r") as f: lines = f.readlines() # Extract the image dimensions from the corresponding image file img_path = os.path.join(yolo_path, file_name.replace(".txt", ".jpg")) img = Image.open(img_path) img_width, img_height = img.size # Create a new VOC annotation file with the same name as the YOLO annotation file xml_file_name = file_name.replace(".txt", ".xml") xml_file_path = os.path.join(voc_path, xml_file_name) root = ET.Element("annotation") ET.SubElement(root, "filename").text = file_name.replace(".txt", ".jpg") size = ET.SubElement(root, "size") ET.SubElement(size, "width").text = str(img_width) ET.SubElement(size, "height").text = str(img_height) # Loop through each line in the YOLO annotation file for line in lines: class_id, x_center, y_center, box_width, box_height = map(float, line.split()) # Convert the YOLO format coordinates to VOC format coordinates x_min = int((x_center - box_width/2) * img_width) y_min = int((y_center - box_height/2) * img_height) x_max = int((x_center + box_width/2) * img_width) y_max = int((y_center + box_height/2) * img_height) # Create a new object element in the VOC annotation file object_tag = ET.SubElement(root, "object") ET.SubElement(object_tag, "name").text = classes[int(class_id)] bndbox = ET.SubElement(object_tag, "bndbox") ET.SubElement(bndbox, "xmin").text = str(x_min) ET.SubElement(bndbox, "ymin").text = str(y_min) ET.SubElement(bndbox, "xmax").text = str(x_max) ET.SubElement(bndbox, "ymax").text = str(y_max) # Write the VOC annotation file to disk tree = ET.ElementTree(root) tree.write(xml_file_path) # Call the function with the YOLO and VOC dataset directory paths yolo_path = "/path/to/yolo/dataset" voc_path = "/path/to/voc/dataset" convert_yolo_to_voc(yolo_path, voc_path) ``` 这段代码YOLO格式数据集目录中的所有文本文件换为VOC格式的XML文件,并将它们保存到指定的目录中。每个XML文件对应于一个图像文件,其中包图像的名称、尺寸和每个对象的边界框。如果您需要更改类别名称,请修改代码中的classes列表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MorleyOlsen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值