/
roi.py
236 lines (198 loc) · 8.99 KB
/
roi.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
class rpn2roi():
def __init__(self):
pass
def img_resize(self,min_side=600):
if self.width <= self.height:
f = float(min_side)/self.width
self.resized_height = int(f*self.height)
self.resized_width = min_side
else:
f = float(min_side)/self.height
self.resized_height = min_side
self.resized_width = int(f*self.width)
def roi_iou(self,R,img_data,config,class_mapping,data_load):
bboxes = img_data['bboxes']
(self.width, self.height) = (img_data['width'], img_data['height'])
self.img_resize()
gta = np.zeros((len(bboxes), 4))
for bbox_num, bbox in enumerate(bboxes):
# get the GT box coordinates, and resize to account for feature_map resizing
gta[bbox_num, 0] = int(round(bbox['x1'] * (self.resized_width / float(self.width))/config.rpn_stride))
gta[bbox_num, 1] = int(round(bbox['x2'] * (self.resized_width / float(self.width))/config.rpn_stride))
gta[bbox_num, 2] = int(round(bbox['y1'] * (self.resized_height / float(self.height))/config.rpn_stride))
gta[bbox_num, 3] = int(round(bbox['y2'] * (self.resized_height / float(self.height))/config.rpn_stride))
x_roi = []
y_class_num = []
y_class_regr_coords = []
y_class_regr_label = []
# traverse all boxes
for ix in range(R.shape[0]):
(x1, y1, x2, y2) = R[ix]
x1 = int(round(x1))
y1 = int(round(y1))
x2 = int(round(x2))
y2 = int(round(y2))
best_iou = 0.0
best_bbox = -1
for bbox_num in range(len(bboxes)):
cur_iou = data_load.iou([gta[bbox_num, 0], gta[bbox_num, 2], gta[bbox_num, 1], gta[bbox_num, 3]], [x1, y1, x2, y2])
if cur_iou > best_iou:
best_iou = cur_iou
best_bbox = bbox_num
if best_iou < config.classifier_min_overlap:
continue
else:
w = x2 - x1
h = y2 - y1
x_roi.append([x1, y1, w, h])
if config.classifier_min_overlap <= best_iou < config.classifier_max_overlap:
# hard negative example
cls_name = 'bg'
elif config.classifier_max_overlap <= best_iou:
cls_name = bboxes[best_bbox]['class']
cxg = (gta[best_bbox, 0] + gta[best_bbox, 1]) / 2.0
cyg = (gta[best_bbox, 2] + gta[best_bbox, 3]) / 2.0
cx = x1 + w / 2.0
cy = y1 + h / 2.0
tx = (cxg - cx) / float(w)
ty = (cyg - cy) / float(h)
tw = np.log((gta[best_bbox, 1] - gta[best_bbox, 0]) / float(w))
th = np.log((gta[best_bbox, 3] - gta[best_bbox, 2]) / float(h))
# prepare for onehot encoding
class_num = class_mapping[cls_name]
class_label = len(class_mapping) * [0]
class_label[class_num] = 1
y_class_num.append(copy.deepcopy(class_label))
coords = [0] * 4 * (len(class_mapping) - 1)
labels = [0] * 4 * (len(class_mapping) - 1)
if cls_name != 'bg':
label_pos = 4 * class_num
sx, sy, sw, sh = config.classifier_regr_std
coords[label_pos:4+label_pos] = [sx*tx, sy*ty, sw*tw, sh*th]
labels[label_pos:4+label_pos] = [1, 1, 1, 1]
y_class_regr_coords.append(copy.deepcopy(coords))
y_class_regr_label.append(copy.deepcopy(labels))
else:
y_class_regr_coords.append(copy.deepcopy(coords))
y_class_regr_label.append(copy.deepcopy(labels))
if len(x_roi) == 0:
return None, None, None
X = np.array(x_roi)
Y1 = np.array(y_class_num)
Y2 = np.concatenate([np.array(y_class_regr_label),np.array(y_class_regr_coords)],axis=1)
return np.expand_dims(X, axis=0), np.expand_dims(Y1, axis=0), np.expand_dims(Y2, axis=0)
def nms(self,config):
self.boxes = self.all_boxes.astype("float")
if len(self.boxes) == 0:
return []
pick = []
x1 = self.boxes[:, 0]
y1 = self.boxes[:, 1]
x2 = self.boxes[:, 2]
y2 = self.boxes[:, 3]
area = (x2 - x1) * (y2 - y1)
idxs = np.argsort(self.all_probs)
'''
Method:
1. first figure out the max prob region
2. IoU > 0.7 then cut it!
3. Go back to (1)
'''
while len(idxs) > 0:
# grab the last index in the indexes list and add the index value to the list of picked indexes
last = len(idxs) - 1
i = idxs[last]
pick.append(i)
xx1_int = np.maximum(x1[i], x1[idxs[:last]])
yy1_int = np.maximum(y1[i], y1[idxs[:last]])
xx2_int = np.minimum(x2[i], x2[idxs[:last]])
yy2_int = np.minimum(y2[i], y2[idxs[:last]])
ww_int = np.maximum(0, xx2_int - xx1_int)
hh_int = np.maximum(0, yy2_int - yy1_int)
area_int = ww_int * hh_int
area_union = area[i] + area[idxs[:last]] - area_int
overlap = area_int/(area_union + 1e-6)
idxs = np.delete(idxs, np.concatenate(([last],np.where(overlap > config.overlap_thresh)[0])))
if len(pick) >= config.max_boxes:
break
self.boxes = self.boxes[pick].astype("int")
self.probs = self.all_probs[pick]
def apply_regr_np(self,X,T):
x = X[0]
y = X[1]
w = X[2]
h = X[3]
tx = T[0]
ty = T[1]
tw = T[2]
th = T[3]
cx = x + w/2.0
cy = y + h/2.0
cx1 = tx * w + cx
cy1 = ty * h + cy
w1 = np.exp(tw.astype(np.float64)) * w
h1 = np.exp(th.astype(np.float64)) * h
x1 = cx1 - w1/2
y1 = cy1 - h1/2
x1 = np.round(x1)
y1 = np.round(y1)
w1 = np.round(w1)
h1 = np.round(h1)
return np.stack([x1,y1,w1,h1])
def rpn_to_roi(self,rpn_layer,regr_layer,config):
regr_layer = regr_layer / config.std_scaling
anchor_sizes = config.anchor_box_scales
anchor_ratios = config.anchor_box_ratios
(rows, cols) = rpn_layer.shape[1:3]
curr_layer = 0
A = np.zeros((4, rpn_layer.shape[1], rpn_layer.shape[2], rpn_layer.shape[3]))
for anchor_size in anchor_sizes:
for anchor_ratio in anchor_ratios:
# find the anchor situation in feature map
anchor_x = (anchor_size * anchor_ratio[0])//config.rpn_stride
anchor_y = (anchor_size * anchor_ratio[1])//config.rpn_stride
# get the regr map in shape(4,height,width)
# regr = at current anchor level
regr = regr_layer[0, :, :, 4 * curr_layer:4 * curr_layer + 4]
regr = np.transpose(regr, (2, 0, 1))
X, Y = np.meshgrid(np.arange(cols),np.arange(rows))
A[0, :, :, curr_layer] = X - anchor_x/2
A[1, :, :, curr_layer] = Y - anchor_y/2
A[2, :, :, curr_layer] = anchor_x
A[3, :, :, curr_layer] = anchor_y
A[:, :, :, curr_layer] = self.apply_regr_np(A[:, :, :, curr_layer], regr)
'''
adjust A
if width or height is smaller than 1, that is 1.
A[2] will be the x1 + w1
A[3] will be the y1 + h1
'''
A[2, :, :, curr_layer] = np.maximum(1, A[2, :, :, curr_layer])
A[3, :, :, curr_layer] = np.maximum(1, A[3, :, :, curr_layer])
A[2, :, :, curr_layer] += A[0, :, :, curr_layer]
A[3, :, :, curr_layer] += A[1, :, :, curr_layer]
'''
adjust A
if x1 or y1 is out of img (<0) then cancel it.
same with x2 and y2.
'''
A[0, :, :, curr_layer] = np.maximum(0, A[0, :, :, curr_layer])
A[1, :, :, curr_layer] = np.maximum(0, A[1, :, :, curr_layer])
A[2, :, :, curr_layer] = np.minimum(cols-1, A[2, :, :, curr_layer])
A[3, :, :, curr_layer] = np.minimum(rows-1, A[3, :, :, curr_layer])
curr_layer += 1
'''
all_boxex.shape(anchor_num * feature_map_width * feature_map_height,4)
all_probs.shape(anchor_num * feature_map_width * feature_map_height,1)
'''
all_boxes = np.reshape(A.transpose((0,3,1,2)), (4, -1)).transpose((1, 0))
all_probs = rpn_layer.transpose((0,3,1,2)).reshape((-1))
x1 = all_boxes[:, 0]
y1 = all_boxes[:, 1]
x2 = all_boxes[:, 2]
y2 = all_boxes[:, 3]
idxs = np.where((x1 - x2 >= 0) | (y1 - y2 >= 0))
self.all_boxes = np.delete(all_boxes, idxs, 0)
self.all_probs = np.delete(all_probs, idxs, 0)
self.nms(config)
return self.boxes,self.probs