CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: hukaixuan19970627/yolov5_obb
Path: blob/master/DOTA_devkit/dota_evaluation_task2.py
Views: 475
1
# --------------------------------------------------------
2
# dota_evaluation_task1
3
# Licensed under The MIT License [see LICENSE for details]
4
# Written by Jian Ding, based on code from Bharath Hariharan
5
# --------------------------------------------------------
6
7
"""
8
To use the code, users should to config detpath, annopath and imagesetfile
9
detpath is the path for 15 result files, for the format, you can refer to "http://captain.whu.edu.cn/DOTAweb/tasks.html"
10
search for PATH_TO_BE_CONFIGURED to config the paths
11
Note, the evaluation is on the large scale images
12
"""
13
import xml.etree.ElementTree as ET
14
import os
15
#import cPickle
16
import numpy as np
17
import matplotlib.pyplot as plt
18
19
def parse_gt(filename):
20
objects = []
21
with open(filename, 'r') as f:
22
lines = f.readlines()
23
splitlines = [x.strip().split(' ') for x in lines]
24
for splitline in splitlines:
25
object_struct = {}
26
if len(splitline) < 9:
27
continue
28
object_struct['name'] = splitline[8]
29
if (len(splitline) == 9):
30
object_struct['difficult'] = 0
31
elif (len(splitline) == 10):
32
object_struct['difficult'] = int(splitline[9])
33
# object_struct['difficult'] = 0
34
object_struct['bbox'] = [int(float(splitline[0])),
35
int(float(splitline[1])),
36
int(float(splitline[4])),
37
int(float(splitline[5]))]
38
w = int(float(splitline[4])) - int(float(splitline[0]))
39
h = int(float(splitline[5])) - int(float(splitline[1]))
40
object_struct['area'] = w * h
41
#print('area:', object_struct['area'])
42
# if object_struct['area'] < (15 * 15):
43
# #print('area:', object_struct['area'])
44
# object_struct['difficult'] = 1
45
objects.append(object_struct)
46
return objects
47
def voc_ap(rec, prec, use_07_metric=False):
48
""" ap = voc_ap(rec, prec, [use_07_metric])
49
Compute VOC AP given precision and recall.
50
If use_07_metric is true, uses the
51
VOC 07 11 point method (default:False).
52
"""
53
if use_07_metric:
54
# 11 point metric
55
ap = 0.
56
for t in np.arange(0., 1.1, 0.1):
57
if np.sum(rec >= t) == 0:
58
p = 0
59
else:
60
p = np.max(prec[rec >= t])
61
ap = ap + p / 11.
62
else:
63
# correct AP calculation
64
# first append sentinel values at the end
65
mrec = np.concatenate(([0.], rec, [1.]))
66
mpre = np.concatenate(([0.], prec, [0.]))
67
68
# compute the precision envelope
69
for i in range(mpre.size - 1, 0, -1):
70
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
71
72
# to calculate area under PR curve, look for points
73
# where X axis (recall) changes value
74
i = np.where(mrec[1:] != mrec[:-1])[0]
75
76
# and sum (\Delta recall) * prec
77
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
78
return ap
79
80
def voc_eval(detpath,
81
annopath,
82
imagesetfile,
83
classname,
84
# cachedir,
85
ovthresh=0.5,
86
use_07_metric=False):
87
"""rec, prec, ap = voc_eval(detpath,
88
annopath,
89
imagesetfile,
90
classname,
91
[ovthresh],
92
[use_07_metric])
93
Top level function that does the PASCAL VOC evaluation.
94
detpath: Path to detections
95
detpath.format(classname) should produce the detection results file.
96
annopath: Path to annotations
97
annopath.format(imagename) should be the xml annotations file.
98
imagesetfile: Text file containing the list of images, one image per line.
99
classname: Category name (duh)
100
cachedir: Directory for caching the annotations
101
[ovthresh]: Overlap threshold (default = 0.5)
102
[use_07_metric]: Whether to use VOC07's 11 point AP computation
103
(default False)
104
"""
105
# assumes detections are in detpath.format(classname)
106
# assumes annotations are in annopath.format(imagename)
107
# assumes imagesetfile is a text file with each line an image name
108
# cachedir caches the annotations in a pickle file
109
110
# first load gt
111
#if not os.path.isdir(cachedir):
112
# os.mkdir(cachedir)
113
#cachefile = os.path.join(cachedir, 'annots.pkl')
114
# read list of images
115
with open(imagesetfile, 'r') as f:
116
lines = f.readlines()
117
imagenames = [x.strip() for x in lines]
118
#print('imagenames: ', imagenames)
119
#if not os.path.isfile(cachefile):
120
# load annots
121
recs = {}
122
for i, imagename in enumerate(imagenames):
123
#print('parse_files name: ', annopath.format(imagename))
124
recs[imagename] = parse_gt(annopath.format(imagename))
125
#if i % 100 == 0:
126
# print ('Reading annotation for {:d}/{:d}'.format(
127
# i + 1, len(imagenames)) )
128
# save
129
#print ('Saving cached annotations to {:s}'.format(cachefile))
130
#with open(cachefile, 'w') as f:
131
# cPickle.dump(recs, f)
132
#else:
133
# load
134
#with open(cachefile, 'r') as f:
135
# recs = cPickle.load(f)
136
137
# extract gt objects for this class
138
class_recs = {}
139
npos = 0
140
for imagename in imagenames:
141
R = [obj for obj in recs[imagename] if obj['name'] == classname]
142
bbox = np.array([x['bbox'] for x in R])
143
difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
144
det = [False] * len(R)
145
npos = npos + sum(~difficult)
146
class_recs[imagename] = {'bbox': bbox,
147
'difficult': difficult,
148
'det': det}
149
150
# read dets
151
detfile = detpath.format(classname)
152
with open(detfile, 'r') as f:
153
lines = f.readlines()
154
155
splitlines = [x.strip().split(' ') for x in lines]
156
image_ids = [x[0] for x in splitlines]
157
confidence = np.array([float(x[1]) for x in splitlines])
158
159
#print('check confidence: ', confidence)
160
161
BB = np.array([[float(z) for z in x[2:]] for x in splitlines])
162
163
# sort by confidence
164
sorted_ind = np.argsort(-confidence)
165
sorted_scores = np.sort(-confidence)
166
167
#print('check sorted_scores: ', sorted_scores)
168
#print('check sorted_ind: ', sorted_ind)
169
BB = BB[sorted_ind, :]
170
image_ids = [image_ids[x] for x in sorted_ind]
171
#print('check imge_ids: ', image_ids)
172
#print('imge_ids len:', len(image_ids))
173
# go down dets and mark TPs and FPs
174
nd = len(image_ids)
175
tp = np.zeros(nd)
176
fp = np.zeros(nd)
177
for d in range(nd):
178
R = class_recs[image_ids[d]]
179
bb = BB[d, :].astype(float)
180
ovmax = -np.inf
181
BBGT = R['bbox'].astype(float)
182
183
if BBGT.size > 0:
184
# compute overlaps
185
# intersection
186
ixmin = np.maximum(BBGT[:, 0], bb[0])
187
iymin = np.maximum(BBGT[:, 1], bb[1])
188
ixmax = np.minimum(BBGT[:, 2], bb[2])
189
iymax = np.minimum(BBGT[:, 3], bb[3])
190
iw = np.maximum(ixmax - ixmin + 1., 0.)
191
ih = np.maximum(iymax - iymin + 1., 0.)
192
inters = iw * ih
193
194
# union
195
uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +
196
(BBGT[:, 2] - BBGT[:, 0] + 1.) *
197
(BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)
198
199
overlaps = inters / uni
200
ovmax = np.max(overlaps)
201
## if there exist 2
202
jmax = np.argmax(overlaps)
203
204
if ovmax > ovthresh:
205
if not R['difficult'][jmax]:
206
if not R['det'][jmax]:
207
tp[d] = 1.
208
R['det'][jmax] = 1
209
else:
210
fp[d] = 1.
211
# print('filename:', image_ids[d])
212
else:
213
fp[d] = 1.
214
215
# compute precision recall
216
217
print('check fp:', fp)
218
print('check tp', tp)
219
220
221
print('npos num:', npos)
222
fp = np.cumsum(fp)
223
tp = np.cumsum(tp)
224
225
rec = tp / float(npos)
226
# avoid divide by zero in case the first detection matches a difficult
227
# ground truth
228
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
229
ap = voc_ap(rec, prec, use_07_metric)
230
231
return rec, prec, ap
232
233
def main():
234
# detpath = r'E:\documentation\OneDrive\documentation\DotaEvaluation\evluation_task2\evluation_task2\faster-rcnn-nms_0.3_task2\nms_0.3_task\Task2_{:s}.txt'
235
# annopath = r'I:\dota\testset\ReclabelTxt-utf-8\{:s}.txt'
236
# imagesetfile = r'I:\dota\testset\va.txt'
237
238
detpath = r'tools/parse_pkl/evaluation_results/dotav2_merged_HBB/Task2_{:s}.txt'
239
annopath = r'/dataset/Dota/Dota_V2.0/val/labelTxt-v2.0/Val_Task2_gt/{:s}.txt'# change the directory to the path of val/labelTxt, if you want to do evaluation on the valset
240
imagesetfile = r'tools/parse_pkl/evaluation_results/imgnamefile_val2.0.txt'
241
242
classnames = [ 'plane', 'baseball-diamond', 'bridge', 'ground-track-field', 'small-vehicle', 'large-vehicle', 'ship',
243
'tennis-court', 'basketball-court', 'storage-tank', 'soccer-ball-field', 'roundabout', 'harbor',
244
'swimming-pool', 'helicopter', 'container-crane', 'airport', 'helipad']
245
classaps = []
246
map = 0
247
for classname in classnames:
248
print('classname:', classname)
249
rec, prec, ap = voc_eval(detpath,
250
annopath,
251
imagesetfile,
252
classname,
253
ovthresh=0.5,
254
use_07_metric=True)
255
map = map + ap
256
#print('rec: ', rec, 'prec: ', prec, 'ap: ', ap)
257
print('ap: ', ap)
258
classaps.append(ap)
259
260
## uncomment to plot p-r curve for each category
261
# plt.figure(figsize=(8,4))
262
# plt.xlabel('recall')
263
# plt.ylabel('precision')
264
# plt.plot(rec, prec)
265
# plt.show()
266
map = map/len(classnames)
267
print('map:', map)
268
classaps = 100*np.array(classaps)
269
print('classaps: ', classaps)
270
if __name__ == '__main__':
271
main()
272