深度学习|dota格式的txt文件转化为yolo格式的txt文件

这篇具有很好参考价值的文章主要介绍了深度学习|dota格式的txt文件转化为yolo格式的txt文件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

最近打比赛用到的SAR舰船目标检测集,赛方给出的是dota格式的标签文件,如图:
dota数据集处理成yolo格式,python,深度学习,python,深度学习,神经网络,计算机视觉
上图中前8个数据代表真实框四个点的坐标(以左上角坐标顺时针旋转),ship是DOTA数据集的分类,最后的0表示识别难易程度是简单,为1表示难。

要用yolo检测必须先把dota标签文件转化为yolo标签文件。转化代码如下,这里使用的是参考程序中的YOLO_Transform.py这个脚本,同时需注意,需要在dota_utils.py中修改类别名称wordname_18。

YOLO_Transform.py
import dota_utils as util
import os
import numpy as np
from PIL import Image

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None


## trans dota format to format YOLO(darknet) required
def dota2darknet(imgpath, txtpath, dstpath, extractclassname):
    """
    :param imgpath: the path of images
    :param txtpath: the path of txt in dota format
    :param dstpath: the path of txt in YOLO format
    :param extractclassname: the category you selected
    :return:
    """
    filelist = util.GetFileFromThisRootDir(txtpath)
    for fullname in filelist:
        objects = util.parse_dota_poly(fullname)
        name = os.path.splitext(os.path.basename(fullname))[0]
        img_fullname = os.path.join(imgpath, name + '.png')
        img = Image.open(img_fullname)
        img_w, img_h = img.size
        # print img_w,img_h
        with open(os.path.join(dstpath, name + '.txt'), 'w') as f_out:
            for obj in objects:
                poly = obj['poly']
                bbox = np.array(util.dots4ToRecC(poly, img_w, img_h))
                if (sum(bbox <= 0) + sum(bbox >= 1)) >= 1:
                    continue
                if (obj['name'] in extractclassname):
                    id = extractclassname.index(obj['name'])
                else:
                    continue
                outline = str(id) + ' ' + ' '.join(list(map(str, bbox)))
                f_out.write(outline + '\n')


if __name__ == '__main__':
    dota2darknet('C:/Users/xy/Desktop/Work/upload/DOTA/train/images',
                 'C:/Users/xy/Desktop/Work/upload/DOTA/train/labels1',
                 'C:/Users/xy/Desktop/Work/upload/DOTA/train/labels',
                 util.wordname_18)

    dota2darknet('C:/Users/xy/Desktop/Work/upload/DOTA/val/images',
                 'C:/Users/xy/Desktop/Work/upload/DOTA/val/labels1',
                 'C:/Users/xy/Desktop/Work/upload/DOTA/val/labels',
                 util.wordname_18)
dota_utils.py
import sys
import codecs
import numpy as np
import shapely.geometry as shgeo
import os
import re
import math
"""
    some basic functions which are useful for process DOTA data
"""

wordname_18 = [
  'airport',
  'small-vehicle',
  'large-vehicle',
  'plane',
  'storage-tank',
  'ship',
  'harbor',
  'ground-track-field',
  'soccer-ball-field',
  'tennis-court',
  'swimming-pool',
  'baseball-diamond',
  'roundabout',
  'basketball-court',
  'bridge',
  'helicopter',
  'container-crane',
  'helipad']


def custombasename(fullname):
    return os.path.basename(os.path.splitext(fullname)[0])

def GetFileFromThisRootDir(dir,ext = None):
  allfiles = []
  needExtFilter = (ext != None)
  for root,dirs,files in os.walk(dir):
    for filespath in files:
      filepath = os.path.join(root, filespath)
      extension = os.path.splitext(filepath)[1][1:]
      if needExtFilter and extension in ext:
        allfiles.append(filepath)
      elif not needExtFilter:
        allfiles.append(filepath)
  return allfiles

def TuplePoly2Poly(poly):
    outpoly = [poly[0][0], poly[0][1],
                       poly[1][0], poly[1][1],
                       poly[2][0], poly[2][1],
                       poly[3][0], poly[3][1]
                       ]
    return outpoly

def parse_dota_poly(filename):
    """
        parse the dota ground truth in the format:
        [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
    """
    objects = []
    #print('filename:', filename)
    f = []
    if (sys.version_info >= (3, 5)):
        fd = open(filename, 'r')
        f = fd
    elif (sys.version_info >= 2.7):
        fd = codecs.open(filename, 'r')
        f = fd
    # count = 0
    while True:
        line = f.readline()
        # count = count + 1
        # if count < 2:
        #     continue
        if line:
            splitlines = line.strip().split(' ')
            object_struct = {}
            ### clear the wrong name after check all the data
            #if (len(splitlines) >= 9) and (splitlines[8] in classname):
            if (len(splitlines) < 9):
                continue
            if (len(splitlines) >= 9):
                    object_struct['name'] = splitlines[8]
            if (len(splitlines) == 9):
                object_struct['difficult'] = '0'
            elif (len(splitlines) >= 10):
                # if splitlines[9] == '1':
                # if (splitlines[9] == 'tr'):
                #     object_struct['difficult'] = '1'
                # else:
                object_struct['difficult'] = splitlines[9]
                # else:
                #     object_struct['difficult'] = 0
            object_struct['poly'] = [(float(splitlines[0]), float(splitlines[1])),
                                     (float(splitlines[2]), float(splitlines[3])),
                                     (float(splitlines[4]), float(splitlines[5])),
                                     (float(splitlines[6]), float(splitlines[7]))
                                     ]
            gtpoly = shgeo.Polygon(object_struct['poly'])
            object_struct['area'] = gtpoly.area
            # poly = list(map(lambda x:np.array(x), object_struct['poly']))
            # object_struct['long-axis'] = max(distance(poly[0], poly[1]), distance(poly[1], poly[2]))
            # object_struct['short-axis'] = min(distance(poly[0], poly[1]), distance(poly[1], poly[2]))
            # if (object_struct['long-axis'] < 15):
            #     object_struct['difficult'] = '1'
            #     global small_count
            #     small_count = small_count + 1
            objects.append(object_struct)
        else:
            break
    return objects

def dots4ToRecC(poly, img_w, img_h):
    xmin, ymin, xmax, ymax = dots4ToRec4(poly)
    x = (xmin + xmax)/2
    y = (ymin + ymax)/2
    w = xmax - xmin
    h = ymax - ymin
    return x/img_w, y/img_h, w/img_w, h/img_h

def parse_dota_poly2(filename):
    """
        parse the dota ground truth in the format:
        [x1, y1, x2, y2, x3, y3, x4, y4]
    """
    objects = parse_dota_poly(filename)
    for obj in objects:
        obj['poly'] = TuplePoly2Poly(obj['poly'])
        obj['poly'] = list(map(int, obj['poly']))
    return objects

def parse_dota_rec(filename):
    """
        parse the dota ground truth in the bounding box format:
        "xmin, ymin, xmax, ymax"
    """
    objects = parse_dota_poly(filename)
    for obj in objects:
        poly = obj['poly']
        bbox = dots4ToRec4(poly)
        obj['bndbox'] = bbox
    return objects
## bounding box transfer for varies format

def dots4ToRec4(poly):
    xmin, xmax, ymin, ymax = min(poly[0][0], min(poly[1][0], min(poly[2][0], poly[3][0]))), \
                            max(poly[0][0], max(poly[1][0], max(poly[2][0], poly[3][0]))), \
                             min(poly[0][1], min(poly[1][1], min(poly[2][1], poly[3][1]))), \
                             max(poly[0][1], max(poly[1][1], max(poly[2][1], poly[3][1])))
    return xmin, ymin, xmax, ymax
def dots4ToRec8(poly):
    xmin, ymin, xmax, ymax = dots4ToRec4(poly)
    return xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax
    #return dots2ToRec8(dots4ToRec4(poly))
def dots2ToRec8(rec):
    xmin, ymin, xmax, ymax = rec[0], rec[1], rec[2], rec[3]
    return xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax

def groundtruth2Task1(srcpath, dstpath):
    filelist = GetFileFromThisRootDir(srcpath)
    # names = [custombasename(x.strip())for x in filelist]
    filedict = {}
    for cls in wordname_15:
        fd = open(os.path.join(dstpath, 'Task1_') + cls + r'.txt', 'w')
        filedict[cls] = fd
    for filepath in filelist:
        objects = parse_dota_poly2(filepath)

        subname = custombasename(filepath)
        pattern2 = re.compile(r'__([\d+\.]+)__\d+___')
        rate = re.findall(pattern2, subname)[0]

        for obj in objects:
            category = obj['name']
            difficult = obj['difficult']
            poly = obj['poly']
            if difficult == '2':
                continue
            if rate == '0.5':
                outline = custombasename(filepath) + ' ' + '1' + ' ' + ' '.join(map(str, poly))
            elif rate == '1':
                outline = custombasename(filepath) + ' ' + '0.8' + ' ' + ' '.join(map(str, poly))
            elif rate == '2':
                outline = custombasename(filepath) + ' ' + '0.6' + ' ' + ' '.join(map(str, poly))

            filedict[category].write(outline + '\n')

def Task2groundtruth_poly(srcpath, dstpath):
    thresh = 0.1
    filedict = {}
    Tasklist = GetFileFromThisRootDir(srcpath, '.txt')

    for Taskfile in Tasklist:
        idname = custombasename(Taskfile).split('_')[-1]
        # idname = datamap_inverse[idname]
        f = open(Taskfile, 'r')
        lines = f.readlines()
        for line in lines:
            if len(line) == 0:
                continue
            # print('line:', line)
            splitline = line.strip().split(' ')
            filename = splitline[0]
            confidence = splitline[1]
            bbox = splitline[2:]
            if float(confidence) > thresh:
                if filename not in filedict:
                    # filedict[filename] = codecs.open(os.path.join(dstpath, filename + '.txt'), 'w', 'utf_16')
                    filedict[filename] = codecs.open(os.path.join(dstpath, filename + '.txt'), 'w')
                # poly = util.dots2ToRec8(bbox)
                poly = bbox
                #               filedict[filename].write(' '.join(poly) + ' ' + idname + '_' + str(round(float(confidence), 2)) + '\n')
            # print('idname:', idname)

            # filedict[filename].write(' '.join(poly) + ' ' + idname + '_' + str(round(float(confidence), 2)) + '\n')

            filedict[filename].write(' '.join(poly) + ' ' + idname + '\n')


def polygonToRotRectangle(bbox):
    """
    :param bbox: The polygon stored in format [x1, y1, x2, y2, x3, y3, x4, y4]
    :return: Rotated Rectangle in format [cx, cy, w, h, theta]
    """
    bbox = np.array(bbox,dtype=np.float32)
    bbox = np.reshape(bbox,newshape=(2,4),order='F')
    angle = math.atan2(-(bbox[0,1]-bbox[0,0]),bbox[1,1]-bbox[1,0])

    center = [[0],[0]]

    for i in range(4):
        center[0] += bbox[0,i]
        center[1] += bbox[1,i]

    center = np.array(center,dtype=np.float32)/4.0

    R = np.array([[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]], dtype=np.float32)

    normalized = np.matmul(R.transpose(),bbox-center)

    xmin = np.min(normalized[0,:])
    xmax = np.max(normalized[0,:])
    ymin = np.min(normalized[1,:])
    ymax = np.max(normalized[1,:])

    w = xmax - xmin + 1
    h = ymax - ymin + 1

    return [float(center[0]),float(center[1]),w,h,angle]

转化成功
dota数据集处理成yolo格式,python,深度学习,python,深度学习,神经网络,计算机视觉

参考博客:【目标检测】YOLO+DOTA:小样本检测策略文章来源地址https://www.toymoban.com/news/detail-607745.html

到了这里,关于深度学习|dota格式的txt文件转化为yolo格式的txt文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 关于目标检测任务中,YOLO(txt格式)标注文件的可视化

    本文是针对yolo标注格式txt文件的可视化脚本介绍  如果是VOC格式的xml文件,参考:关于目标检测任务中,XML(voc格式)标注文件的可视化 代码比较简单, 50行这样 。。。。 下面是代码的目录结构,1.jpeg 是数据图像,1.txt是对应的相对坐标信息和索引类别 result.png 是保存的绘制

    2024年02月03日
    浏览(49)
  • YOLO格式数据集(.txt)如何转换为VOC格式数据集(.xml)

    前言: 安装好python环境与编译器 转换: 将标注文件从文本格式( .txt )转换为 XML 格式( .xml )可以通过以下步骤完成: 解析文本标注文件:打开 .txt 文件,逐行读取每个标注,并解析边界框坐标和类别信息。 创建 XML 文件:使用 Python 的内置库 xml.etree.ElementTree 创建一个

    2024年02月12日
    浏览(30)
  • YOLO目标检测——棉花病虫害数据集+已标注txt格式标签下载分享

    实际项目应用 :棉花病虫害防治 数据集说明 :棉花病虫害检测数据集,真实场景的高质量图片数据,数据场景丰富 标签说明 :使用lableimg标注软件标注,标注框质量高,含voc(xml)、coco(json)和yolo(txt)三种格式标签,分别存放在不同文件夹下,可以直接用于YOLO系列的目标检测

    2024年02月09日
    浏览(34)
  • YOLO目标检测——口罩规范佩戴数据集+已标注xml和txt格式标签下载分享

    实际项目应用 :疫情防控、智能安检、公共场所监控场景下的大密度人群检测是否佩戴口罩 数据集说明 :人脸口罩规范佩戴数据集,真实场景的高质量图片数据,数据场景丰富,含有正确佩戴口罩、未正确佩戴口罩和没佩戴口罩图片 标签说明 :使用lableimg标注软件标注,标

    2024年02月09日
    浏览(43)
  • 深度学习制作自己的数据集—为数据集打上标签保存为txt文件,并进行划分和加载数据集

    目录 0 前言 1 为图片数据集打上标签并保存为txt文件 2 将txt文件中的图片标签数据集随机划分为训练集和测试集 3 加载txt文件中的图片标签数据集       目前是被封控的第四天了,只能呆在宿舍不能出去,记得上次这样子还是一年前大四快毕业那时候了……       这几天在

    2024年02月02日
    浏览(33)
  • 批量将txt文件转化为excel文件

    可以使用Python的内置库csv和openpyxl来完成这个任务。以下是一个基本的代码示例: import csv from openpyxl import Workbook # 遍历目录中的所有.txt文件 for filename in glob.glob(\\\'*.txt\\\'):     with open(filename, \\\'r\\\') as infile:         reader = csv.reader(infile, delimiter=\\\',\\\')         # 创建新的.xlsx文件    

    2024年02月12日
    浏览(33)
  • 【深度学习】数据集打标签:生成train.txt和val.txt

    当我们在Github上下载一篇论文的代码后,我们如何在自己的数据集上进行复现呢? 准备自己的数据集 这是在百度爬的十分类的服装数据集,其中train文件夹下每类大概300张,val文件夹下每类大概100张,总共在4000张左右。 设置目录 我们将taming作为根目录,在taming下新建data-

    2024年02月09日
    浏览(26)
  • ROS系列——提取bag文件中的数据并保存为csv、txt格式

    实际应用中经常会用到将bag包中的topic数据,保存到csv文件或者txt文件下,然后在对数据进行分析。 其中:为bag文件名,为ros中的Topic名称,为要保存的csv文件名 举例: 其实与csv格式基本一样,只需要修改后缀即可 举例: 注:感谢吕博士提供的支持

    2024年02月14日
    浏览(38)
  • 如何把利用paddlepaddle导出的json文件转化为yolo或者voc文件

    目录 1. 修改源码,让模型能够生成出对于单个图像的标注。 2. 把数据转为yolo格式 3.把yolo格式转化为xml格式 这两天想偷懒,想让模型先在数据上标一遍,然后我再做修正,主要是图个省事。由于我们主要是利用paddle,模型也是基于paddle推理的,因此即便我对paddle有一万个吐槽

    2024年02月07日
    浏览(29)
  • 【Matlab】如何读取文件夹下所有txt数据进行处理并以txt结果更名输出

    如何读取文件夹下所有txt数据进行处理并以txt结果更名输出 目录 前言 一、Matlab中fullfile函数用法 二、使用步骤 1.读取文件夹下所有txt文件并以struct存储变量 2.循环下读取每个txt文件中的数据并进行处理 总结 遇到Matlab需要大批量处理一个文件夹下所有的txt格式,经过信号处

    2024年02月07日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包