hank1996 commited on
Commit
b212448
·
1 Parent(s): 7e10b33

Create new file

Browse files
Files changed (1) hide show
  1. lib/core/postprocess.py +223 -0
lib/core/postprocess.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import torch
4
+ from lib.utils import is_parallel
5
+ import numpy as np
6
+ np.set_printoptions(threshold=np.inf)
7
+ import cv2
8
+ from sklearn.cluster import DBSCAN
9
+
10
+
11
+ def build_targets(cfg, predictions, targets, model):
12
+ '''
13
+ predictions
14
+ [16, 3, 32, 32, 85]
15
+ [16, 3, 16, 16, 85]
16
+ [16, 3, 8, 8, 85]
17
+ torch.tensor(predictions[i].shape)[[3, 2, 3, 2]]
18
+ [32,32,32,32]
19
+ [16,16,16,16]
20
+ [8,8,8,8]
21
+ targets[3,x,7]
22
+ t [index, class, x, y, w, h, head_index]
23
+ '''
24
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
25
+ det = model.module.model[model.module.detector_index] if is_parallel(model) \
26
+ else model.model[model.detector_index] # Detect() module
27
+ # print(type(model))
28
+ # det = model.model[model.detector_index]
29
+ # print(type(det))
30
+ na, nt = det.na, targets.shape[0] # number of anchors, targets
31
+ tcls, tbox, indices, anch = [], [], [], []
32
+ gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
33
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
34
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
35
+
36
+ g = 0.5 # bias
37
+ off = torch.tensor([[0, 0],
38
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
39
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
40
+ ], device=targets.device).float() * g # offsets
41
+
42
+ for i in range(det.nl):
43
+ anchors = det.anchors[i] #[3,2]
44
+ gain[2:6] = torch.tensor(predictions[i].shape)[[3, 2, 3, 2]] # xyxy gain
45
+ # Match targets to anchors
46
+ t = targets * gain
47
+
48
+ if nt:
49
+ # Matches
50
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
51
+ j = torch.max(r, 1. / r).max(2)[0] < cfg.TRAIN.ANCHOR_THRESHOLD # compare
52
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
53
+ t = t[j] # filter
54
+
55
+ # Offsets
56
+ gxy = t[:, 2:4] # grid xy
57
+ gxi = gain[[2, 3]] - gxy # inverse
58
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
59
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
60
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
61
+ t = t.repeat((5, 1, 1))[j]
62
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
63
+ else:
64
+ t = targets[0]
65
+ offsets = 0
66
+
67
+ # Define
68
+ b, c = t[:, :2].long().T # image, class
69
+ gxy = t[:, 2:4] # grid xy
70
+ gwh = t[:, 4:6] # grid wh
71
+ gij = (gxy - offsets).long()
72
+ gi, gj = gij.T # grid xy indices
73
+
74
+ # Append
75
+ a = t[:, 6].long() # anchor indices
76
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
77
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
78
+ anch.append(anchors[a]) # anchors
79
+ tcls.append(c) # class
80
+
81
+ return tcls, tbox, indices, anch
82
+
83
+ def morphological_process(image, kernel_size=5, func_type=cv2.MORPH_CLOSE):
84
+ """
85
+ morphological process to fill the hole in the binary segmentation result
86
+ :param image:
87
+ :param kernel_size:
88
+ :return:
89
+ """
90
+ if len(image.shape) == 3:
91
+ raise ValueError('Binary segmentation result image should be a single channel image')
92
+
93
+ if image.dtype is not np.uint8:
94
+ image = np.array(image, np.uint8)
95
+
96
+ kernel = cv2.getStructuringElement(shape=cv2.MORPH_ELLIPSE, ksize=(kernel_size, kernel_size))
97
+
98
+ # close operation fille hole
99
+ closing = cv2.morphologyEx(image, func_type, kernel, iterations=1)
100
+
101
+ return closing
102
+
103
+ def connect_components_analysis(image):
104
+ """
105
+ connect components analysis to remove the small components
106
+ :param image:
107
+ :return:
108
+ """
109
+ if len(image.shape) == 3:
110
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
111
+ else:
112
+ gray_image = image
113
+ # print(gray_image.dtype)
114
+ return cv2.connectedComponentsWithStats(gray_image, connectivity=8, ltype=cv2.CV_32S)
115
+
116
+ def if_y(samples_x):
117
+ for sample_x in samples_x:
118
+ if len(sample_x):
119
+ # if len(sample_x) != (sample_x[-1] - sample_x[0] + 1) or sample_x[-1] == sample_x[0]:
120
+ if sample_x[-1] == sample_x[0]:
121
+ return False
122
+ return True
123
+
124
+ def fitlane(mask, sel_labels, labels, stats):
125
+ H, W = mask.shape
126
+ for label_group in sel_labels:
127
+ states = [stats[k] for k in label_group]
128
+ x, y, w, h, _ = states[0]
129
+ # if len(label_group) > 1:
130
+ # print('in')
131
+ # for m in range(len(label_group)-1):
132
+ # labels[labels == label_group[m+1]] = label_group[0]
133
+ t = label_group[0]
134
+ # samples_y = np.linspace(y, H-1, 30)
135
+ # else:
136
+ samples_y = np.linspace(y, y+h-1, 30)
137
+
138
+ samples_x = [np.where(labels[int(sample_y)]==t)[0] for sample_y in samples_y]
139
+
140
+ if if_y(samples_x):
141
+ samples_x = [int(np.mean(sample_x)) if len(sample_x) else -1 for sample_x in samples_x]
142
+ samples_x = np.array(samples_x)
143
+ samples_y = np.array(samples_y)
144
+ samples_y = samples_y[samples_x != -1]
145
+ samples_x = samples_x[samples_x != -1]
146
+ func = np.polyfit(samples_y, samples_x, 2)
147
+ x_limits = np.polyval(func, H-1)
148
+ # if (y_max + h - 1) >= 720:
149
+ if x_limits < 0 or x_limits > W:
150
+ # if (y_max + h - 1) > 720:
151
+ # draw_y = np.linspace(y, 720-1, 720-y)
152
+ draw_y = np.linspace(y, y+h-1, h)
153
+ else:
154
+ # draw_y = np.linspace(y, y+h-1, y+h-y)
155
+ draw_y = np.linspace(y, H-1, H-y)
156
+ draw_x = np.polyval(func, draw_y)
157
+ # draw_y = draw_y[draw_x < W]
158
+ # draw_x = draw_x[draw_x < W]
159
+ draw_points = (np.asarray([draw_x, draw_y]).T).astype(np.int32)
160
+ cv2.polylines(mask, [draw_points], False, 1, thickness=15)
161
+ else:
162
+ # if ( + w - 1) >= 1280:
163
+ samples_x = np.linspace(x, W-1, 30)
164
+ # else:
165
+ # samples_x = np.linspace(x, x_max+w-1, 30)
166
+ samples_y = [np.where(labels[:, int(sample_x)]==t)[0] for sample_x in samples_x]
167
+ samples_y = [int(np.mean(sample_y)) if len(sample_y) else -1 for sample_y in samples_y]
168
+ samples_x = np.array(samples_x)
169
+ samples_y = np.array(samples_y)
170
+ samples_x = samples_x[samples_y != -1]
171
+ samples_y = samples_y[samples_y != -1]
172
+ try:
173
+ func = np.polyfit(samples_x, samples_y, 2)
174
+ except:
175
+ pass
176
+ # y_limits = np.polyval(func, 0)
177
+ # if y_limits > 720 or y_limits < 0:
178
+ # if (x + w - 1) >= 1280:
179
+ # draw_x = np.linspace(x, 1280-1, 1280-x)
180
+ # else:
181
+ y_limits = np.polyval(func, 0)
182
+ if y_limits >= H or y_limits < 0:
183
+ draw_x = np.linspace(x, x+w-1, w+x-x)
184
+ else:
185
+ y_limits = np.polyval(func, W-1)
186
+ if y_limits >= H or y_limits < 0:
187
+ draw_x = np.linspace(x, x+w-1, w+x-x)
188
+ # if x+w-1 < 640:
189
+ # draw_x = np.linspace(0, x+w-1, w+x-x)
190
+ else:
191
+ draw_x = np.linspace(x, W-1, W-x)
192
+ draw_y = np.polyval(func, draw_x)
193
+ draw_points = (np.asarray([draw_x, draw_y]).T).astype(np.int32)
194
+ cv2.polylines(mask, [draw_points], False, 1, thickness=15)
195
+ return mask
196
+
197
+ def connect_lane(image, shadow_height=0):
198
+ if len(image.shape) == 3:
199
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
200
+ else:
201
+ gray_image = image
202
+ if shadow_height:
203
+ image[:shadow_height] = 0
204
+ mask = np.zeros((image.shape[0], image.shape[1]), np.uint8)
205
+
206
+ num_labels, labels, stats, centers = cv2.connectedComponentsWithStats(gray_image, connectivity=8, ltype=cv2.CV_32S)
207
+ # ratios = []
208
+ selected_label = []
209
+
210
+ for t in range(1, num_labels, 1):
211
+ _, _, _, _, area = stats[t]
212
+ if area > 400:
213
+ selected_label.append(t)
214
+ if len(selected_label) == 0:
215
+ return mask
216
+ else:
217
+ split_labels = [[label,] for label in selected_label]
218
+ mask_post = fitlane(mask, split_labels, labels, stats)
219
+ return mask_post
220
+
221
+
222
+
223
+