generate_result.py 7.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import re
import glob
M
Manuel Garcia 已提交
18

19 20 21 22 23 24
import numpy as np
from multiprocessing import Pool
from functools import partial
from shapely.geometry import Polygon
import argparse

W
wangxinxin08 已提交
25
wordname_15 = [
26 27 28 29 30 31
    'plane', 'baseball-diamond', 'bridge', 'ground-track-field',
    'small-vehicle', 'large-vehicle', 'ship', 'tennis-court',
    'basketball-court', 'storage-tank', 'soccer-ball-field', 'roundabout',
    'harbor', 'swimming-pool', 'helicopter'
]

W
wangxinxin08 已提交
32 33 34 35 36 37 38 39 40
wordname_16 = wordname_15 + ['container-crane']

wordname_18 = wordname_16 + ['airport', 'helipad']

DATA_CLASSES = {
    'dota10': wordname_15,
    'dota15': wordname_16,
    'dota20': wordname_18
}
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80


def rbox_iou(g, p):
    """
    iou of rbox
    """
    g = np.array(g)
    p = np.array(p)
    g = Polygon(g[:8].reshape((4, 2)))
    p = Polygon(p[:8].reshape((4, 2)))
    g = g.buffer(0)
    p = p.buffer(0)
    if not g.is_valid or not p.is_valid:
        return 0
    inter = Polygon(g).intersection(Polygon(p)).area
    union = g.area + p.area - inter
    if union == 0:
        return 0
    else:
        return inter / union


def py_cpu_nms_poly_fast(dets, thresh):
    """
    Args:
        dets: pred results
        thresh: nms threshold

    Returns: index of keep
    """
    obbs = dets[:, 0:-1]
    x1 = np.min(obbs[:, 0::2], axis=1)
    y1 = np.min(obbs[:, 1::2], axis=1)
    x2 = np.max(obbs[:, 0::2], axis=1)
    y2 = np.max(obbs[:, 1::2], axis=1)
    scores = dets[:, 8]
    areas = (x2 - x1 + 1) * (y2 - y1 + 1)

    polys = []
    for i in range(len(dets)):
M
Manuel Garcia 已提交
81 82 83 84
        tm_polygon = [
            dets[i][0], dets[i][1], dets[i][2], dets[i][3], dets[i][4],
            dets[i][5], dets[i][6], dets[i][7]
        ]
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
        polys.append(tm_polygon)
    polys = np.array(polys)
    order = scores.argsort()[::-1]

    keep = []
    while order.size > 0:
        ovr = []
        i = order[0]
        keep.append(i)

        xx1 = np.maximum(x1[i], x1[order[1:]])
        yy1 = np.maximum(y1[i], y1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])
        w = np.maximum(0.0, xx2 - xx1)
        h = np.maximum(0.0, yy2 - yy1)
        hbb_inter = w * h
        hbb_ovr = hbb_inter / (areas[i] + areas[order[1:]] - hbb_inter)
        h_inds = np.where(hbb_ovr > 0)[0]
        tmp_order = order[h_inds + 1]
        for j in range(tmp_order.size):
            iou = rbox_iou(polys[i], polys[tmp_order[j]])
            hbb_ovr[h_inds[j]] = iou

        try:
            if math.isnan(ovr[0]):
                pdb.set_trace()
        except:
            pass
        inds = np.where(hbb_ovr <= thresh)[0]

        order = order[inds + 1]
    return keep


def poly2origpoly(poly, x, y, rate):
    origpoly = []
M
Manuel Garcia 已提交
122
    for i in range(int(len(poly) / 2)):
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        tmp_x = float(poly[i * 2] + x) / float(rate)
        tmp_y = float(poly[i * 2 + 1] + y) / float(rate)
        origpoly.append(tmp_x)
        origpoly.append(tmp_y)
    return origpoly


def nmsbynamedict(nameboxdict, nms, thresh):
    """
    Args:
        nameboxdict: nameboxdict
        nms:   nms
        thresh: nms threshold

    Returns: nms result as dict
    """
    nameboxnmsdict = {x: [] for x in nameboxdict}
    for imgname in nameboxdict:
        keep = nms(np.array(nameboxdict[imgname]), thresh)
        outdets = []
        for index in keep:
            outdets.append(nameboxdict[imgname][index])
        nameboxnmsdict[imgname] = outdets
    return nameboxnmsdict


W
wangxinxin08 已提交
149
def merge_single(output_dir, nms, nms_thresh, pred_class_lst):
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    """
    Args:
        output_dir: output_dir
        nms:  nms
        pred_class_lst: pred_class_lst
        class_name: class_name

    Returns:

    """
    class_name, pred_bbox_list = pred_class_lst
    nameboxdict = {}
    for line in pred_bbox_list:
        splitline = line.split(' ')
        subname = splitline[0]
        splitname = subname.split('__')
        oriname = splitname[0]
        pattern1 = re.compile(r'__\d+___\d+')
        x_y = re.findall(pattern1, subname)
        x_y_2 = re.findall(r'\d+', x_y[0])
        x, y = int(x_y_2[0]), int(x_y_2[1])

        pattern2 = re.compile(r'__([\d+\.]+)__\d+___')

        rate = re.findall(pattern2, subname)[0]

        confidence = splitline[1]
        poly = list(map(float, splitline[2:]))
        origpoly = poly2origpoly(poly, x, y, rate)
        det = origpoly
        det.append(confidence)
        det = list(map(float, det))
        if (oriname not in nameboxdict):
            nameboxdict[oriname] = []
        nameboxdict[oriname].append(det)
    nameboxnmsdict = nmsbynamedict(nameboxdict, nms, nms_thresh)

    # write result
    dstname = os.path.join(output_dir, class_name + '.txt')
    with open(dstname, 'w') as f_out:
        for imgname in nameboxnmsdict:
            for det in nameboxnmsdict[imgname]:
                confidence = det[-1]
                bbox = det[0:-1]
M
Manuel Garcia 已提交
194 195
                outline = imgname + ' ' + str(confidence) + ' ' + ' '.join(
                    map(str, bbox))
196 197 198
                f_out.write(outline + '\n')


W
wangxinxin08 已提交
199 200 201 202
def generate_result(pred_txt_dir,
                    output_dir='output',
                    class_names=wordname_15,
                    nms_thresh=0.1):
203 204 205
    """
    pred_txt_dir: dir of pred txt
    output_dir: dir of output
W
wangxinxin08 已提交
206
    class_names: class names of data
207 208 209 210 211
    """
    pred_txt_list = glob.glob("{}/*.txt".format(pred_txt_dir))

    # step1: summary pred bbox
    pred_classes = {}
W
wangxinxin08 已提交
212
    for class_name in class_names:
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        pred_classes[class_name] = []

    for current_txt in pred_txt_list:
        img_id = os.path.split(current_txt)[1]
        img_id = img_id.split('.txt')[0]
        with open(current_txt) as f:
            res = f.readlines()
            for item in res:
                item = item.split(' ')
                pred_class = item[0]
                item[0] = img_id
                pred_bbox = ' '.join(item)
                pred_classes[pred_class].append(pred_bbox)

    pred_classes_lst = []
    for class_name in pred_classes.keys():
M
Manuel Garcia 已提交
229 230
        print('class_name: {}, count: {}'.format(class_name,
                                                 len(pred_classes[class_name])))
231 232 233
        pred_classes_lst.append((class_name, pred_classes[class_name]))

    # step2: merge
W
wangxinxin08 已提交
234
    pool = Pool(len(class_names))
235
    nms = py_cpu_nms_poly_fast
W
wangxinxin08 已提交
236
    mergesingle_fn = partial(merge_single, output_dir, nms, nms_thresh)
237 238 239
    pool.map(mergesingle_fn, pred_classes_lst)


W
wangxinxin08 已提交
240 241 242 243 244
def parse_args():
    parser = argparse.ArgumentParser(description='generate test results')
    parser.add_argument('--pred_txt_dir', type=str, help='path of pred txt dir')
    parser.add_argument(
        '--output_dir', type=str, default='output', help='path of output dir')
M
Manuel Garcia 已提交
245
    parser.add_argument(
W
wangxinxin08 已提交
246
        '--data_type', type=str, default='dota10', help='data type')
247
    parser.add_argument(
W
wangxinxin08 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261
        '--nms_thresh',
        type=float,
        default=0.1,
        help='nms threshold whild merging results')

    return parser.parse_args()


if __name__ == '__main__':
    args = parse_args()

    output_dir = args.output_dir
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
262

W
wangxinxin08 已提交
263
    class_names = DATA_CLASSES[args.data_type]
264

W
wangxinxin08 已提交
265
    generate_result(args.pred_txt_dir, output_dir, class_names)
266
    print('done!')