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/ResultEnsembleNMS_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:193# splitline = [(该目标所处图片名称), confidence, x1, y1, x2, y2, x3, y3, x4, y4]194#subname = splitline[0]195oriname = splitline[0]196#splitname = subname.split('__')197#oriname = splitname[0]198# pattern1 = re.compile(r'__\d+___\d+')199# #print('subname:', subname)200# x_y = re.findall(pattern1, subname)201# x_y_2 = re.findall(r'\d+', x_y[0])202# x, y = int(x_y_2[0]), int(x_y_2[1])203204# pattern2 = re.compile(r'__([\d+\.]+)__\d+___')205206# rate = re.findall(pattern2, subname)[0]207208confidence = splitline[1]209poly = list(map(float, splitline[2:]))210#origpoly = poly2origpoly(poly, x, y, rate)211det = poly # shape(8)212det.append(confidence)213det = list(map(float, det))214if (oriname not in nameboxdict):215nameboxdict[oriname] = []216nameboxdict[oriname].append(det)217nameboxnmsdict = nmsbynamedict(nameboxdict, nms, nms_thresh)218with open(dstname, 'w') as f_out:219for imgname in nameboxnmsdict:220for det in nameboxnmsdict[imgname]:221#print('det:', det)222confidence = det[-1]223confidence = round(confidence, 2)224bbox = det[0:-1]225226bbox[0] = round(bbox[0], 1)227bbox[1] = round(bbox[1], 1)228bbox[2] = round(bbox[2], 1)229bbox[3] = round(bbox[3], 1)230bbox[4] = round(bbox[4], 1)231bbox[5] = round(bbox[5], 1)232bbox[6] = round(bbox[6], 1)233bbox[7] = round(bbox[7], 1)234235outline = imgname + ' ' + str(confidence) + ' ' + ' '.join(map(str, bbox))236#print('outline:', outline)237f_out.write(outline + '\n')238239def mergebase_parallel(srcpath, dstpath, nms):240pool = Pool(16)241filelist = util.GetFileFromThisRootDir(srcpath)242243mergesingle_fn = partial(mergesingle, dstpath, nms)244# pdb.set_trace()245pool.map(mergesingle_fn, filelist)246247def mergebase(srcpath, dstpath, nms):248filelist = util.GetFileFromThisRootDir(srcpath)249for filename in filelist:250mergesingle(dstpath, nms, filename)251252def mergebyrec(srcpath, dstpath):253"""254srcpath: result files before merge and nms255dstpath: result files after merge and nms256"""257# srcpath = r'E:\bod-dataset\results\bod-v3_rfcn_2000000'258# dstpath = r'E:\bod-dataset\results\bod-v3_rfcn_2000000_nms'259if os.path.exists(dstpath):260shutil.rmtree(dstpath) # delete output folderX261os.makedirs(dstpath)262263mergebase(srcpath,264dstpath,265py_cpu_nms)266def mergebypoly(srcpath, dstpath):267"""268srcpath: result files before merge and nms269dstpath: result files after merge and nms270"""271# srcpath = r'/home/dingjian/evaluation_task1/result/faster-rcnn-59/comp4_test_results'272# dstpath = r'/home/dingjian/evaluation_task1/result/faster-rcnn-59/testtime'273if os.path.exists(dstpath):274shutil.rmtree(dstpath) # delete output folderX275os.makedirs(dstpath)276277# mergebase(srcpath,278# dstpath,279# py_cpu_nms_poly)280mergebase_parallel(srcpath,281dstpath,282py_cpu_nms_poly_fast)283284def parse_args():285parser = argparse.ArgumentParser(description='MMDet test (and eval) a model')286parser.add_argument('--scrpath', default='/OrientedRepPoints/tools/parse_pkl/evaluation_results/orientedreppoints_ROIRT_ensemble', help='test config file path')287parser.add_argument('--dstpath', default='/OrientedRepPoints/tools/parse_pkl/evaluation_results/orientedreppoints_ROIRT_ensemble_nms', help='checkpoint file')288args = parser.parse_args()289return args290291if __name__ == '__main__':292args = parse_args()293294mergebypoly(srcpath=args.scrpath,295dstpath=args.dstpath)296print('Result Merge Done!')297# mergebyrec()298299