国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

深度學(xué)習(xí)|dota格式的txt文件轉(zhuǎn)化為yolo格式的txt文件

這篇具有很好參考價值的文章主要介紹了深度學(xué)習(xí)|dota格式的txt文件轉(zhuǎn)化為yolo格式的txt文件。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

最近打比賽用到的SAR艦船目標(biāo)檢測集,賽方給出的是dota格式的標(biāo)簽文件,如圖:
dota數(shù)據(jù)集處理成yolo格式,python,深度學(xué)習(xí),python,深度學(xué)習(xí),神經(jīng)網(wǎng)絡(luò),計算機視覺
上圖中前8個數(shù)據(jù)代表真實框四個點的坐標(biāo)(以左上角坐標(biāo)順時針旋轉(zhuǎn)),ship是DOTA數(shù)據(jù)集的分類,最后的0表示識別難易程度是簡單,為1表示難。

要用yolo檢測必須先把dota標(biāo)簽文件轉(zhuǎn)化為yolo標(biāo)簽文件。轉(zhuǎn)化代碼如下,這里使用的是參考程序中的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]

轉(zhuǎn)化成功
dota數(shù)據(jù)集處理成yolo格式,python,深度學(xué)習(xí),python,深度學(xué)習(xí),神經(jīng)網(wǎng)絡(luò),計算機視覺

參考博客:【目標(biāo)檢測】YOLO+DOTA:小樣本檢測策略文章來源地址http://www.zghlxwxcb.cn/news/detail-607745.html

到了這里,關(guān)于深度學(xué)習(xí)|dota格式的txt文件轉(zhuǎn)化為yolo格式的txt文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 關(guān)于目標(biāo)檢測任務(wù)中,YOLO(txt格式)標(biāo)注文件的可視化

    關(guān)于目標(biāo)檢測任務(wù)中,YOLO(txt格式)標(biāo)注文件的可視化

    本文是針對yolo標(biāo)注格式txt文件的可視化腳本介紹? 如果是VOC格式的xml文件,參考:關(guān)于目標(biāo)檢測任務(wù)中,XML(voc格式)標(biāo)注文件的可視化 代碼比較簡單, 50行這樣 。。。。 下面是代碼的目錄結(jié)構(gòu),1.jpeg 是數(shù)據(jù)圖像,1.txt是對應(yīng)的相對坐標(biāo)信息和索引類別 result.png 是保存的繪制

    2024年02月03日
    瀏覽(98)
  • YOLO格式數(shù)據(jù)集(.txt)如何轉(zhuǎn)換為VOC格式數(shù)據(jù)集(.xml)

    前言: 安裝好python環(huán)境與編譯器 轉(zhuǎn)換: 將標(biāo)注文件從文本格式( .txt )轉(zhuǎn)換為 XML 格式( .xml )可以通過以下步驟完成: 解析文本標(biāo)注文件:打開 .txt 文件,逐行讀取每個標(biāo)注,并解析邊界框坐標(biāo)和類別信息。 創(chuàng)建 XML 文件:使用 Python 的內(nèi)置庫 xml.etree.ElementTree 創(chuàng)建一個

    2024年02月12日
    瀏覽(24)
  • YOLO目標(biāo)檢測——棉花病蟲害數(shù)據(jù)集+已標(biāo)注txt格式標(biāo)簽下載分享

    YOLO目標(biāo)檢測——棉花病蟲害數(shù)據(jù)集+已標(biāo)注txt格式標(biāo)簽下載分享

    實際項目應(yīng)用 :棉花病蟲害防治 數(shù)據(jù)集說明 :棉花病蟲害檢測數(shù)據(jù)集,真實場景的高質(zhì)量圖片數(shù)據(jù),數(shù)據(jù)場景豐富 標(biāo)簽說明 :使用lableimg標(biāo)注軟件標(biāo)注,標(biāo)注框質(zhì)量高,含voc(xml)、coco(json)和yolo(txt)三種格式標(biāo)簽,分別存放在不同文件夾下,可以直接用于YOLO系列的目標(biāo)檢測

    2024年02月09日
    瀏覽(55)
  • YOLO目標(biāo)檢測——口罩規(guī)范佩戴數(shù)據(jù)集+已標(biāo)注xml和txt格式標(biāo)簽下載分享

    YOLO目標(biāo)檢測——口罩規(guī)范佩戴數(shù)據(jù)集+已標(biāo)注xml和txt格式標(biāo)簽下載分享

    實際項目應(yīng)用 :疫情防控、智能安檢、公共場所監(jiān)控場景下的大密度人群檢測是否佩戴口罩 數(shù)據(jù)集說明 :人臉口罩規(guī)范佩戴數(shù)據(jù)集,真實場景的高質(zhì)量圖片數(shù)據(jù),數(shù)據(jù)場景豐富,含有正確佩戴口罩、未正確佩戴口罩和沒佩戴口罩圖片 標(biāo)簽說明 :使用lableimg標(biāo)注軟件標(biāo)注,標(biāo)

    2024年02月09日
    瀏覽(32)
  • 深度學(xué)習(xí)制作自己的數(shù)據(jù)集—為數(shù)據(jù)集打上標(biāo)簽保存為txt文件,并進行劃分和加載數(shù)據(jù)集

    深度學(xué)習(xí)制作自己的數(shù)據(jù)集—為數(shù)據(jù)集打上標(biāo)簽保存為txt文件,并進行劃分和加載數(shù)據(jù)集

    目錄 0 前言 1 為圖片數(shù)據(jù)集打上標(biāo)簽并保存為txt文件 2 將txt文件中的圖片標(biāo)簽數(shù)據(jù)集隨機劃分為訓(xùn)練集和測試集 3 加載txt文件中的圖片標(biāo)簽數(shù)據(jù)集 ? ? ? 目前是被封控的第四天了,只能呆在宿舍不能出去,記得上次這樣子還是一年前大四快畢業(yè)那時候了…… ? ? ? 這幾天在

    2024年02月02日
    瀏覽(35)
  • 批量將txt文件轉(zhuǎn)化為excel文件

    可以使用Python的內(nèi)置庫csv和openpyxl來完成這個任務(wù)。以下是一個基本的代碼示例: import csv from openpyxl import Workbook # 遍歷目錄中的所有.txt文件 for filename in glob.glob(\\\'*.txt\\\'): ? ? with open(filename, \\\'r\\\') as infile: ? ? ? ? reader = csv.reader(infile, delimiter=\\\',\\\') ? ? ? ? # 創(chuàng)建新的.xlsx文件 ? ?

    2024年02月12日
    瀏覽(19)
  • 【深度學(xué)習(xí)】數(shù)據(jù)集打標(biāo)簽:生成train.txt和val.txt

    【深度學(xué)習(xí)】數(shù)據(jù)集打標(biāo)簽:生成train.txt和val.txt

    當(dāng)我們在Github上下載一篇論文的代碼后,我們?nèi)绾卧谧约旱臄?shù)據(jù)集上進行復(fù)現(xiàn)呢? 準(zhǔn)備自己的數(shù)據(jù)集 這是在百度爬的十分類的服裝數(shù)據(jù)集,其中train文件夾下每類大概300張,val文件夾下每類大概100張,總共在4000張左右。 設(shè)置目錄 我們將taming作為根目錄,在taming下新建data-

    2024年02月09日
    瀏覽(24)
  • ROS系列——提取bag文件中的數(shù)據(jù)并保存為csv、txt格式

    實際應(yīng)用中經(jīng)常會用到將bag包中的topic數(shù)據(jù),保存到csv文件或者txt文件下,然后在對數(shù)據(jù)進行分析。 其中:為bag文件名,為ros中的Topic名稱,為要保存的csv文件名 舉例: 其實與csv格式基本一樣,只需要修改后綴即可 舉例: 注:感謝呂博士提供的支持

    2024年02月14日
    瀏覽(157)
  • 如何把利用paddlepaddle導(dǎo)出的json文件轉(zhuǎn)化為yolo或者voc文件

    如何把利用paddlepaddle導(dǎo)出的json文件轉(zhuǎn)化為yolo或者voc文件

    目錄 1. 修改源碼,讓模型能夠生成出對于單個圖像的標(biāo)注。 2. 把數(shù)據(jù)轉(zhuǎn)為yolo格式 3.把yolo格式轉(zhuǎn)化為xml格式 這兩天想偷懶,想讓模型先在數(shù)據(jù)上標(biāo)一遍,然后我再做修正,主要是圖個省事。由于我們主要是利用paddle,模型也是基于paddle推理的,因此即便我對paddle有一萬個吐槽

    2024年02月07日
    瀏覽(24)
  • 【Matlab】如何讀取文件夾下所有txt數(shù)據(jù)進行處理并以txt結(jié)果更名輸出

    如何讀取文件夾下所有txt數(shù)據(jù)進行處理并以txt結(jié)果更名輸出 目錄 前言 一、Matlab中fullfile函數(shù)用法 二、使用步驟 1.讀取文件夾下所有txt文件并以struct存儲變量 2.循環(huán)下讀取每個txt文件中的數(shù)據(jù)并進行處理 總結(jié) 遇到Matlab需要大批量處理一個文件夾下所有的txt格式,經(jīng)過信號處

    2024年02月07日
    瀏覽(152)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包