【目标检测】旋转目标检测COCO格式标注转DOTAv1格式

DOTAv1数据集格式:

'imagesource':imagesource
'gsd':gsd
x1, y1, x2, y2, x3, y3, x4, y4, category, difficult
x1, y1, x2, y2, x3, y3, x4, y4, category, difficult
...

imagesource: 图片来源  
gsd: 分辨率
x1, y1, x2, y2, x3, y3, x4, y4:四边形的四个顶点的坐标 顶点按顺时针顺序排列,第一个起点为左上第一个点
category:实例类别
difficult:表示该实例是否难以检测(1表示困难,0表示不困难)

COCO转DOTA:

import json
import cv2
import numpy as np
import os

def calculate_rotated_bbox(poly):
    """将多边形坐标转换为旋转边界框"""
    contour = np.array(poly).reshape((-1, 1, 2)).astype(np.float32)
    rect = cv2.minAreaRect(contour)
    box = cv2.boxPoints(rect)
    return np.int0(box)

def coco_to_dota(coco_annotation_path, dota_annotation_folder, imagesource="Unknown", gsd="Unknown"):
    """将COCO格式的标注转换为DOTA格式,包括imagesource和gsd信息"""
    # 类别ID到名称的映射
    category_map = {
        1: 'Class1',
        2: 'Class2',
    }

    # 确保输出目录存在
    if not os.path.exists(dota_annotation_folder):
        os.makedirs(dota_annotation_folder)

    # 读取COCO格式的JSON文件
    with open(coco_annotation_path, 'r') as f:
        coco_data = json.load(f)

    # 遍历每个图像的标注
    for image in coco_data['images']:
        image_id = image['id']
        image_filename = image['file_name']
        dota_filename = os.path.splitext(image_filename)[0] + '.txt'  # 去掉原始扩展名,添加.txt
        dota_filepath = os.path.join(dota_annotation_folder, dota_filename)

        with open(dota_filepath, 'w') as dota_file:
            # 写入imagesource和gsd信息
            # dota_file.write(f"'imagesource':{imagesource}\n'gsd':{gsd}\n")

            # 找到当前图像的所有标注
            for annotation in filter(lambda x: x['image_id'] == image_id, coco_data['annotations']):
                if 'segmentation' in annotation:
                    for seg in annotation['segmentation']:
                        if type(seg[0]) is list:  # 检查是否是多边形格式
                            seg = seg[0]
                        box = calculate_rotated_bbox(seg)
                        # 从映射中获取类别名称
                        category_name = category_map.get(annotation['category_id'], 'Unknown')
                        # 格式化DOTA标注
                        box_str = ' '.join(map(str, box.flatten().tolist()))
                        dota_annotation = f"{box_str} {category_name} 0\n"
                        dota_file.write(dota_annotation)


# 调用函数,转换COCO到DOTA
coco_annotation_path = 'instances.json'
dota_annotation_folder = 'dota'
coco_to_dota(coco_annotation_path, dota_annotation_folder)

标注可视化:

import cv2
import numpy as np
import os


def draw_rotated_box(img, box, label):
    """在图像上绘制旋转的边界框和标签。"""
    points = np.int0(box)
    cv2.drawContours(img, [points], 0, (0, 255, 0), 2)  # 绘制旋转框
    cv2.putText(img, label, tuple(points[0]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)  # 添加文本标签


def visualize_dota_annotations(image_folder, annotation_folder, output_folder):
    """批量处理图像和DOTA标注文件,绘制旋转边界框和标签"""
    # 确保输出文件夹存在
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 遍历图像文件
    for img_filename in os.listdir(image_folder):
        img_path = os.path.join(image_folder, img_filename)
        if os.path.isfile(img_path) and img_filename.endswith(('.jpg', '.png')):
            annot_filename = os.path.splitext(img_filename)[0] + '.txt'
            annot_path = os.path.join(annotation_folder, annot_filename)
            output_img_path = os.path.join(output_folder, img_filename)

            img = cv2.imread(img_path)
            if img is None:
                continue

            if os.path.isfile(annot_path):
                with open(annot_path, 'r') as f:
                    lines = f.readlines()  # Skip imagesource and gsd lines
                    for line in lines:
                        parts = line.strip().split(' ')
                        if len(parts) < 9:
                            continue
                        box = np.array([float(part) for part in parts[:8]]).reshape(4, 2)
                        label = parts[8]
                        draw_rotated_box(img, box, label)

            cv2.imwrite(output_img_path, img)

# 路径配置
image_folder = 'images'
annotation_folder = 'dota'
output_folder = 'visual'

visualize_dota_annotations(image_folder, annotation_folder, output_folder)

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用R3Det训练自己的数据集,你需要进行以下几个步骤: 1. 下载R3Det代码。你可以在GitHub上找到R3Det的代码链接。下载并配置好代码。 2. 配置训练脚本。修改train.py文件的配置参数,主要是--config和--work-dir。--config是指向训练配置文件的路径,--work-dir是指定模型和日志保存的文件夹。 3. 修改配置文件。根据你的需求,选择一个适合的配置文件进行修改。例如,你可以选择r3det_r50_fpn_1x_dota_oc.py作为配置文件,根据你的类别数量修改num_classes参数。同时,你还需要修改mmrotate/mmrotate/datasets/dota.py中的类别名字。 4. 修改数据文件夹路径。在mmrotate/configs/base/datasets/dotav1.py中修改data_root参数,将其设置为你自己的数据文件夹路径。该文件夹应包括train、trainval和test三个文件夹,并在这三个文件夹内部创建annfiles和images文件夹,并将相应的数据文件放入其中。 5. 调整训练参数。你可以根据需要修改其他的训练参数。例如,在configs/base/schedules/schedule_1x.py中可以调整评估的间隔、优化器的学习率和动量等参数。 6. 开始训练。运行train.py脚本,即可开始使用R3Det训练自己的数据集。训练过程中的模型和日志将保存在指定的work-dir文件夹中。 请注意,以上步骤仅为一般指导,具体的操作可能因你的数据集和需求而有所不同。你需要根据实际情况进行相应的修改和调整。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [R3Det代码复现](https://blog.csdn.net/m0_64203255/article/details/130025291)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [mmrotate旋转目标检测架从环境配置到训练自己的数据集](https://blog.csdn.net/weixin_41868104/article/details/125557687)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值