Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/DOTA_devkit/dota_utils.py
Views: 475
import sys1import codecs2import numpy as np3import shapely.geometry as shgeo4import os5import re6import math7# import polyiou8"""9some basic functions which are useful for process DOTA data10"""1112wordname_15 = ['plane', 'baseball-diamond', 'bridge', 'ground-track-field', 'small-vehicle', 'large-vehicle', 'ship', 'tennis-court',13'basketball-court', 'storage-tank', 'soccer-ball-field', 'roundabout', 'harbor', 'swimming-pool', 'helicopter']1415CLASSNAMES = ['plane', 'baseball-diamond', 'bridge', 'ground-track-field', 'small-vehicle', 'large-vehicle', 'ship', 'tennis-court',16'basketball-court', 'storage-tank', 'soccer-ball-field', 'roundabout', 'harbor', 'swimming-pool', 'helicopter', 'container-crane']171819def custombasename(fullname):20return os.path.basename(os.path.splitext(fullname)[0])212223def GetFileFromThisRootDir(dir, ext=None):24allfiles = []25needExtFilter = (ext != None)26for root, dirs, files in os.walk(dir):27for filespath in files:28filepath = os.path.join(root, filespath)29extension = os.path.splitext(filepath)[1][1:]30if needExtFilter and extension in ext:31allfiles.append(filepath)32elif not needExtFilter:33allfiles.append(filepath)34return allfiles353637def TuplePoly2Poly(poly):38outpoly = [poly[0][0], poly[0][1],39poly[1][0], poly[1][1],40poly[2][0], poly[2][1],41poly[3][0], poly[3][1]42]43return outpoly444546def parse_dota_poly(filename):47"""48parse the dota ground truth in the format:49[(x1, y1), (x2, y2), (x3, y3), (x4, y4)]50"""51objects = []52#print('filename:', filename)53f = []54if (sys.version_info >= (3, 5)):55fd = open(filename, 'r')56f = fd57elif (sys.version_info >= 2.7):58fd = codecs.open(filename, 'r')59f = fd60# count = 061while True:62line = f.readline()63# count = count + 164# if count < 2:65# continue66if line:67splitlines = line.strip().split(' ')68object_struct = {}69# clear the wrong name after check all the data70# if (len(splitlines) >= 9) and (splitlines[8] in classname):71if (len(splitlines) < 9):72continue73if (len(splitlines) >= 9):74object_struct['name'] = splitlines[8]75if (len(splitlines) == 9):76object_struct['difficult'] = '0'77elif (len(splitlines) >= 10):78# if splitlines[9] == '1':79# if (splitlines[9] == 'tr'):80# object_struct['difficult'] = '1'81# else:82object_struct['difficult'] = splitlines[9]83# else:84# object_struct['difficult'] = 085object_struct['poly'] = [(float(splitlines[0]), float(splitlines[1])),86(float(splitlines[2]),87float(splitlines[3])),88(float(splitlines[4]),89float(splitlines[5])),90(float(splitlines[6]),91float(splitlines[7]))92]93gtpoly = shgeo.Polygon(object_struct['poly'])94object_struct['area'] = gtpoly.area95# poly = list(map(lambda x:np.array(x), object_struct['poly']))96# object_struct['long-axis'] = max(distance(poly[0], poly[1]), distance(poly[1], poly[2]))97# object_struct['short-axis'] = min(distance(poly[0], poly[1]), distance(poly[1], poly[2]))98# if (object_struct['long-axis'] < 15):99# object_struct['difficult'] = '1'100# global small_count101# small_count = small_count + 1102objects.append(object_struct)103else:104break105return objects106107108def parse_dota_poly2(filename):109"""110parse the dota ground truth in the format:111[x1, y1, x2, y2, x3, y3, x4, y4]112"""113objects = parse_dota_poly(filename)114for obj in objects:115obj['poly'] = TuplePoly2Poly(obj['poly'])116obj['poly'] = list(map(int, obj['poly']))117return objects118119120def parse_dota_rec(filename):121"""122parse the dota ground truth in the bounding box format:123"xmin, ymin, xmax, ymax"124"""125objects = parse_dota_poly(filename)126for obj in objects:127poly = obj['poly']128bbox = dots4ToRec4(poly)129obj['bndbox'] = bbox130return objects131# bounding box transfer for varies format132133134def dots4ToRec4(poly):135xmin, xmax, ymin, ymax = min(poly[0][0], min(poly[1][0], min(poly[2][0], poly[3][0]))), \136max(poly[0][0], max(poly[1][0], max(poly[2][0], poly[3][0]))), \137min(poly[0][1], min(poly[1][1], min(poly[2][1], poly[3][1]))), \138max(poly[0][1], max(poly[1][1], max(poly[2][1], poly[3][1])))139return xmin, ymin, xmax, ymax140141142def dots4ToRec8(poly):143xmin, ymin, xmax, ymax = dots4ToRec4(poly)144return xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax145# return dots2ToRec8(dots4ToRec4(poly))146147148def dots2ToRec8(rec):149xmin, ymin, xmax, ymax = rec[0], rec[1], rec[2], rec[3]150return xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax151152153def groundtruth2Task1(srcpath, dstpath):154filelist = GetFileFromThisRootDir(srcpath)155# names = [custombasename(x.strip())for x in filelist]156filedict = {}157for cls in wordname_15:158fd = open(os.path.join(dstpath, 'Task1_') + cls + r'.txt', 'w')159filedict[cls] = fd160for filepath in filelist:161objects = parse_dota_poly2(filepath)162163subname = custombasename(filepath)164pattern2 = re.compile(r'__([\d+\.]+)__\d+___')165rate = re.findall(pattern2, subname)[0]166167for obj in objects:168category = obj['name']169difficult = obj['difficult']170poly = obj['poly']171if difficult == '2':172continue173if rate == '0.5':174outline = custombasename(175filepath) + ' ' + '1' + ' ' + ' '.join(map(str, poly))176elif rate == '1':177outline = custombasename(178filepath) + ' ' + '0.8' + ' ' + ' '.join(map(str, poly))179elif rate == '2':180outline = custombasename(181filepath) + ' ' + '0.6' + ' ' + ' '.join(map(str, poly))182183filedict[category].write(outline + '\n')184185186def Task2groundtruth_poly(srcpath, dstpath):187thresh = 0.1188filedict = {}189Tasklist = GetFileFromThisRootDir(srcpath, '.txt')190191for Taskfile in Tasklist:192idname = custombasename(Taskfile).split('_')[-1]193# idname = datamap_inverse[idname]194f = open(Taskfile, 'r')195lines = f.readlines()196for line in lines:197if len(line) == 0:198continue199# print('line:', line)200splitline = line.strip().split(' ')201filename = splitline[0]202confidence = splitline[1]203bbox = splitline[2:]204if float(confidence) > thresh:205if filename not in filedict:206# filedict[filename] = codecs.open(os.path.join(dstpath, filename + '.txt'), 'w', 'utf_16')207filedict[filename] = codecs.open(208os.path.join(dstpath, filename + '.txt'), 'w')209# poly = util.dots2ToRec8(bbox)210poly = bbox211# filedict[filename].write(' '.join(poly) + ' ' + idname + '_' + str(round(float(confidence), 2)) + '\n')212# print('idname:', idname)213214# filedict[filename].write(' '.join(poly) + ' ' + idname + '_' + str(round(float(confidence), 2)) + '\n')215216filedict[filename].write(' '.join(poly) + ' ' + idname + '\n')217218219def polygonToRotRectangle(bbox):220"""221:param bbox: The polygon stored in format [x1, y1, x2, y2, x3, y3, x4, y4]222:return: Rotated Rectangle in format [cx, cy, w, h, theta]223"""224bbox = np.array(bbox, dtype=np.float32)225bbox = np.reshape(bbox, newshape=(2, 4), order='F')226angle = math.atan2(-(bbox[0, 1]-bbox[0, 0]), bbox[1, 1]-bbox[1, 0])227228center = [[0], [0]]229230for i in range(4):231center[0] += bbox[0, i]232center[1] += bbox[1, i]233234center = np.array(center, dtype=np.float32)/4.0235236R = np.array([[math.cos(angle), -math.sin(angle)],237[math.sin(angle), math.cos(angle)]], dtype=np.float32)238239normalized = np.matmul(R.transpose(), bbox-center)240241xmin = np.min(normalized[0, :])242xmax = np.max(normalized[0, :])243ymin = np.min(normalized[1, :])244ymax = np.max(normalized[1, :])245246w = xmax - xmin + 1247h = ymax - ymin + 1248249return [float(center[0]), float(center[1]), w, h, angle]250251252def cal_line_length(point1, point2):253return math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2))254255256def get_best_begin_point(coordinate):257x1 = coordinate[0][0]258y1 = coordinate[0][1]259x2 = coordinate[1][0]260y2 = coordinate[1][1]261x3 = coordinate[2][0]262y3 = coordinate[2][1]263x4 = coordinate[3][0]264y4 = coordinate[3][1]265xmin = min(x1, x2, x3, x4)266ymin = min(y1, y2, y3, y4)267xmax = max(x1, x2, x3, x4)268ymax = max(y1, y2, y3, y4)269combinate = [[[x1, y1], [x2, y2], [x3, y3], [x4, y4]], [[x2, y2], [x3, y3], [x4, y4], [x1, y1]],270[[x3, y3], [x4, y4], [x1, y1], [x2, y2]], [[x4, y4], [x1, y1], [x2, y2], [x3, y3]]]271dst_coordinate = [[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]272force = 100000000.0273force_flag = 0274for i in range(4):275temp_force = cal_line_length(combinate[i][0], dst_coordinate[0]) + cal_line_length(combinate[i][1],276dst_coordinate[2771]) + cal_line_length(278combinate[i][2], dst_coordinate[2]) + cal_line_length(combinate[i][3], dst_coordinate[3])279if temp_force < force:280force = temp_force281force_flag = i282if force_flag != 0:283print("choose one direction!")284return combinate[force_flag]285286287