forked from clovaai/wsolevaluation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
125 lines (100 loc) · 4.2 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
81
82
83
84
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
122
123
124
125
"""
Copyright (c) 2020-present NAVER Corp.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import json
import numpy as np
import os
import sys
class Logger(object):
"""Log stdout messages."""
def __init__(self, outfile):
self.terminal = sys.stdout
self.log = open(outfile, "w")
sys.stdout = self
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
self.terminal.flush()
def t2n(t):
return t.detach().cpu().numpy().astype(np.float)
def check_scoremap_validity(scoremap):
if not isinstance(scoremap, np.ndarray):
raise TypeError("Scoremap must be a numpy array; it is {}."
.format(type(scoremap)))
if scoremap.dtype != np.float:
raise TypeError("Scoremap must be of np.float type; it is of {} type."
.format(scoremap.dtype))
if len(scoremap.shape) != 2:
raise ValueError("Scoremap must be a 2D array; it is {}D."
.format(len(scoremap.shape)))
if np.isnan(scoremap).any():
raise ValueError("Scoremap must not contain nans.")
if (scoremap > 1).any() or (scoremap < 0).any():
raise ValueError("Scoremap must be in range [0, 1]."
"scoremap.min()={}, scoremap.max()={}."
.format(scoremap.min(), scoremap.max()))
def string_contains_any(string, substring_list):
for substring in substring_list:
if substring in string:
return True
return False
class Reporter(object):
def __init__(self, reporter_log_root, epoch):
self.log_file = os.path.join(reporter_log_root, str(epoch))
self.epoch = epoch
self.report_dict = {
'summary': True,
'step': self.epoch,
}
def add(self, key, val):
self.report_dict.update({key: val})
def write(self):
log_file = self.log_file
while os.path.isfile(log_file):
log_file += '_'
with open(log_file, 'w') as f:
f.write(json.dumps(self.report_dict))
def check_box_convention(boxes, convention):
"""
Args:
boxes: numpy.ndarray(dtype=np.int or np.float, shape=(num_boxes, 4))
convention: string. One of ['x0y0x1y1', 'xywh'].
Raises:
RuntimeError if box does not meet the convention.
"""
if (boxes < 0).any():
raise RuntimeError("Box coordinates must be non-negative.")
if len(boxes.shape) == 1:
boxes = np.expand_dims(boxes, 0)
elif len(boxes.shape) != 2:
raise RuntimeError("Box array must have dimension (4) or "
"(num_boxes, 4).")
if boxes.shape[1] != 4:
raise RuntimeError("Box array must have dimension (4) or "
"(num_boxes, 4).")
if convention == 'x0y0x1y1':
widths = boxes[:, 2] - boxes[:, 0]
heights = boxes[:, 3] - boxes[:, 1]
elif convention == 'xywh':
widths = boxes[:, 2]
heights = boxes[:, 3]
else:
raise ValueError("Unknown convention {}.".format(convention))
if (widths < 0).any() or (heights < 0).any():
raise RuntimeError("Boxes do not follow the {} convention."
.format(convention))