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/ResultMerge_multi_process.py
Views: 475
"""1To use the code, users should to config detpath, annopath and imagesetfile2detpath is the path for 15 result files, for the format, you can refer to "http://captain.whu.edu.cn/DOTAweb/tasks.html"3search for PATH_TO_BE_CONFIGURED to config the paths4Note, the evaluation is on the large scale images5"""6import os7import numpy as np8import re9import time10import sys11sys.path.insert(0,'..')12import DOTA_devkit.dota_utils as util13import DOTA_devkit.polyiou as polyiou14import pdb15import math16from multiprocessing import Pool17from functools import partial18import shutil19import argparse2021## the thresh for nms when merge image22nms_thresh = 0.22324def py_cpu_nms_poly(dets, thresh):25scores = dets[:, 8]26polys = []27areas = []28for i in range(len(dets)):29tm_polygon = polyiou.VectorDouble([dets[i][0], dets[i][1],30dets[i][2], dets[i][3],31dets[i][4], dets[i][5],32dets[i][6], dets[i][7]])33polys.append(tm_polygon)34order = scores.argsort()[::-1]3536keep = []37while order.size > 0:38ovr = []39i = order[0]40keep.append(i)41for j in range(order.size - 1):42iou = polyiou.iou_poly(polys[i], polys[order[j + 1]])43ovr.append(iou)44ovr = np.array(ovr)4546# print('ovr: ', ovr)47# print('thresh: ', thresh)48try:49if math.isnan(ovr[0]):50pdb.set_trace()51except:52pass53inds = np.where(ovr <= thresh)[0]54# print('inds: ', inds)5556order = order[inds + 1]5758return keep596061def py_cpu_nms_poly_fast(dets, thresh):62obbs = dets[:, 0:-1]63x1 = np.min(obbs[:, 0::2], axis=1)64y1 = np.min(obbs[:, 1::2], axis=1)65x2 = np.max(obbs[:, 0::2], axis=1)66y2 = np.max(obbs[:, 1::2], axis=1)67scores = dets[:, 8]68areas = (x2 - x1 + 1) * (y2 - y1 + 1)6970polys = []71for i in range(len(dets)):72tm_polygon = polyiou.VectorDouble([dets[i][0], dets[i][1],73dets[i][2], dets[i][3],74dets[i][4], dets[i][5],75dets[i][6], dets[i][7]])76polys.append(tm_polygon)77order = scores.argsort()[::-1]7879keep = []80while order.size > 0:81ovr = []82i = order[0]83keep.append(i)84# if order.size == 0:85# break86xx1 = np.maximum(x1[i], x1[order[1:]])87yy1 = np.maximum(y1[i], y1[order[1:]])88xx2 = np.minimum(x2[i], x2[order[1:]])89yy2 = np.minimum(y2[i], y2[order[1:]])90# w = np.maximum(0.0, xx2 - xx1 + 1)91# h = np.maximum(0.0, yy2 - yy1 + 1)92w = np.maximum(0.0, xx2 - xx1)93h = np.maximum(0.0, yy2 - yy1)94hbb_inter = w * h95hbb_ovr = hbb_inter / (areas[i] + areas[order[1:]] - hbb_inter)96# h_keep_inds = np.where(hbb_ovr == 0)[0]97h_inds = np.where(hbb_ovr > 0)[0]98tmp_order = order[h_inds + 1]99for j in range(tmp_order.size):100iou = polyiou.iou_poly(polys[i], polys[tmp_order[j]])101hbb_ovr[h_inds[j]] = iou102# ovr.append(iou)103# ovr_index.append(tmp_order[j])104105# ovr = np.array(ovr)106# ovr_index = np.array(ovr_index)107# print('ovr: ', ovr)108# print('thresh: ', thresh)109try:110if math.isnan(ovr[0]):111pdb.set_trace()112except:113pass114inds = np.where(hbb_ovr <= thresh)[0]115116# order_obb = ovr_index[inds]117# print('inds: ', inds)118# order_hbb = order[h_keep_inds + 1]119order = order[inds + 1]120# pdb.set_trace()121# order = np.concatenate((order_obb, order_hbb), axis=0).astype(np.int)122return keep123124def py_cpu_nms(dets, thresh):125"""Pure Python NMS baseline."""126#print('dets:', dets)127x1 = dets[:, 0]128y1 = dets[:, 1]129x2 = dets[:, 2]130y2 = dets[:, 3]131scores = dets[:, 4]132133areas = (x2 - x1 + 1) * (y2 - y1 + 1)134## index for dets135order = scores.argsort()[::-1]136137138keep = []139while order.size > 0:140i = order[0]141keep.append(i)142xx1 = np.maximum(x1[i], x1[order[1:]])143yy1 = np.maximum(y1[i], y1[order[1:]])144xx2 = np.minimum(x2[i], x2[order[1:]])145yy2 = np.minimum(y2[i], y2[order[1:]])146147w = np.maximum(0.0, xx2 - xx1 + 1)148h = np.maximum(0.0, yy2 - yy1 + 1)149inter = w * h150ovr = inter / (areas[i] + areas[order[1:]] - inter)151152inds = np.where(ovr <= thresh)[0]153order = order[inds + 1]154155return keep156157def nmsbynamedict(nameboxdict, nms, thresh):158nameboxnmsdict = {x: [] for x in nameboxdict}159for imgname in nameboxdict:160#print('imgname:', imgname)161#keep = py_cpu_nms(np.array(nameboxdict[imgname]), thresh)162#print('type nameboxdict:', type(nameboxnmsdict))163#print('type imgname:', type(imgname))164#print('type nms:', type(nms))165keep = nms(np.array(nameboxdict[imgname]), thresh)166#print('keep:', keep)167outdets = []168#print('nameboxdict[imgname]: ', nameboxnmsdict[imgname])169for index in keep:170# print('index:', index)171outdets.append(nameboxdict[imgname][index])172nameboxnmsdict[imgname] = outdets173return nameboxnmsdict174def poly2origpoly(poly, x, y, rate):175origpoly = []176for i in range(int(len(poly)/2)):177tmp_x = float(poly[i * 2] + x) / float(rate)178tmp_y = float(poly[i * 2 + 1] + y) / float(rate)179origpoly.append(tmp_x)180origpoly.append(tmp_y)181return origpoly182183def mergesingle(dstpath, nms, fullname):184name = util.custombasename(fullname)185#print('name:', name)186dstname = os.path.join(dstpath, name + '.txt')187print(dstname)188with open(fullname, 'r') as f_in:189nameboxdict = {}190lines = f_in.readlines()191splitlines = [x.strip().split(' ') for x in lines]192for splitline in splitlines:193subname = splitline[0]194splitname = subname.split('__')195oriname = splitname[0]196pattern1 = re.compile(r'__\d+___\d+')197#print('subname:', subname)198x_y = re.findall(pattern1, subname)199x_y_2 = re.findall(r'\d+', x_y[0])200x, y = int(x_y_2[0]), int(x_y_2[1])201202pattern2 = re.compile(r'__([\d+\.]+)__\d+___')203204rate = re.findall(pattern2, subname)[0]205206confidence = splitline[1]207poly = list(map(float, splitline[2:]))208origpoly = poly2origpoly(poly, x, y, rate)209det = origpoly210det.append(confidence)211det = list(map(float, det))212if (oriname not in nameboxdict):213nameboxdict[oriname] = []214nameboxdict[oriname].append(det)215nameboxnmsdict = nmsbynamedict(nameboxdict, nms, nms_thresh)216with open(dstname, 'w') as f_out:217for imgname in nameboxnmsdict:218for det in nameboxnmsdict[imgname]:219#print('det:', det)220confidence = det[-1]221confidence = round(confidence, 2)222bbox = det[0:-1]223224bbox[0] = round(bbox[0], 1)225bbox[1] = round(bbox[1], 1)226bbox[2] = round(bbox[2], 1)227bbox[3] = round(bbox[3], 1)228bbox[4] = round(bbox[4], 1)229bbox[5] = round(bbox[5], 1)230bbox[6] = round(bbox[6], 1)231bbox[7] = round(bbox[7], 1)232233outline = imgname + ' ' + str(confidence) + ' ' + ' '.join(map(str, bbox))234#print('outline:', outline)235f_out.write(outline + '\n')236237def mergebase_parallel(srcpath, dstpath, nms):238pool = Pool(16)239filelist = util.GetFileFromThisRootDir(srcpath)240241mergesingle_fn = partial(mergesingle, dstpath, nms)242# pdb.set_trace()243pool.map(mergesingle_fn, filelist)244245def mergebase(srcpath, dstpath, nms):246filelist = util.GetFileFromThisRootDir(srcpath)247for filename in filelist:248mergesingle(dstpath, nms, filename)249250def mergebyrec(srcpath, dstpath):251"""252srcpath: result files before merge and nms253dstpath: result files after merge and nms254"""255# srcpath = r'E:\bod-dataset\results\bod-v3_rfcn_2000000'256# dstpath = r'E:\bod-dataset\results\bod-v3_rfcn_2000000_nms'257if os.path.exists(dstpath):258shutil.rmtree(dstpath) # delete output folderX259os.makedirs(dstpath)260261mergebase(srcpath,262dstpath,263py_cpu_nms)264def mergebypoly(srcpath, dstpath):265"""266srcpath: result files before merge and nms267dstpath: result files after merge and nms268"""269# srcpath = r'/home/dingjian/evaluation_task1/result/faster-rcnn-59/comp4_test_results'270# dstpath = r'/home/dingjian/evaluation_task1/result/faster-rcnn-59/testtime'271if os.path.exists(dstpath):272shutil.rmtree(dstpath) # delete output folderX273os.makedirs(dstpath)274275# mergebase(srcpath,276# dstpath,277# py_cpu_nms_poly)278mergebase_parallel(srcpath,279dstpath,280py_cpu_nms_poly_fast)281282def parse_args():283parser = argparse.ArgumentParser(description='MMDet test (and eval) a model')284parser.add_argument('--scrpath', default='/home/test/Persons/hukaixuan/YOLOX/YOLOX_outputs/exp_train_dotav15_gap200/results/best_ckpt', help='test config file path')285parser.add_argument('--dstpath', default='/home/test/Persons/hukaixuan/YOLOX/YOLOX_outputs/exp_train_dotav15_gap200/results/best_ckpt_nms', help='checkpoint file')286args = parser.parse_args()287return args288289if __name__ == '__main__':290args = parse_args()291292mergebypoly(srcpath=args.scrpath,293dstpath=args.dstpath)294print('Result Merge Done!')295# mergebyrec()296297