hank1996 commited on
Commit
efbf861
·
1 Parent(s): 6cde260

Update utils/functions.py

Browse files
Files changed (1) hide show
  1. utils/functions.py +522 -0
utils/functions.py CHANGED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import datetime
4
+ import logging
5
+ import os
6
+ import platform
7
+ import subprocess
8
+ import time
9
+ from pathlib import Path
10
+ import re
11
+ import glob
12
+ import random
13
+ import cv2
14
+ import numpy as np
15
+ import torch
16
+ import torchvision
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def git_describe(path=Path(__file__).parent): # path must be a directory
22
+ # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
23
+ s = f'git -C {path} describe --tags --long --always'
24
+ try:
25
+ return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
26
+ except subprocess.CalledProcessError as e:
27
+ return '' # not a git repository
28
+
29
+ def date_modified(path=__file__):
30
+ # return human-readable file modification date, i.e. '2021-3-26'
31
+ t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
32
+ return f'{t.year}-{t.month}-{t.day}'
33
+
34
+ def select_device(device='', batch_size=None):
35
+ # device = 'cpu' or '0' or '0,1,2,3'
36
+ s = f'YOLOPv2 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
37
+ cpu = device.lower() == 'cpu'
38
+ if cpu:
39
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
40
+ elif device: # non-cpu device requested
41
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
42
+ assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
43
+
44
+ cuda = not cpu and torch.cuda.is_available()
45
+ if cuda:
46
+ n = torch.cuda.device_count()
47
+ if n > 1 and batch_size: # check that batch_size is compatible with device_count
48
+ assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
49
+ space = ' ' * len(s)
50
+ for i, d in enumerate(device.split(',') if device else range(n)):
51
+ p = torch.cuda.get_device_properties(i)
52
+ s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
53
+ else:
54
+ s += 'CPU\n'
55
+
56
+ logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
57
+ return torch.device('cuda:0' if cuda else 'cpu')
58
+
59
+
60
+ def time_synchronized():
61
+ # pytorch-accurate time
62
+ if torch.cuda.is_available():
63
+ torch.cuda.synchronize()
64
+ return time.time()
65
+
66
+ def plot_one_box(x, img, color=None, label=None, line_thickness=3):
67
+ # Plots one bounding box on image img
68
+ tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
69
+ color = color or [random.randint(0, 255) for _ in range(3)]
70
+ c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
71
+ cv2.rectangle(img, c1, c2, [0,255,255], thickness=2, lineType=cv2.LINE_AA)
72
+ if label:
73
+ tf = max(tl - 1, 1) # font thickness
74
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
75
+ c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
76
+
77
+ class SegmentationMetric(object):
78
+ '''
79
+ imgLabel [batch_size, height(144), width(256)]
80
+ confusionMatrix [[0(TN),1(FP)],
81
+ [2(FN),3(TP)]]
82
+ '''
83
+ def __init__(self, numClass):
84
+ self.numClass = numClass
85
+ self.confusionMatrix = np.zeros((self.numClass,)*2)
86
+
87
+ def pixelAccuracy(self):
88
+ # return all class overall pixel accuracy
89
+ # acc = (TP + TN) / (TP + TN + FP + TN)
90
+ acc = np.diag(self.confusionMatrix).sum() / self.confusionMatrix.sum()
91
+ return acc
92
+
93
+ def lineAccuracy(self):
94
+ Acc = np.diag(self.confusionMatrix) / (self.confusionMatrix.sum(axis=1) + 1e-12)
95
+ return Acc[1]
96
+
97
+ def classPixelAccuracy(self):
98
+ # return each category pixel accuracy(A more accurate way to call it precision)
99
+ # acc = (TP) / TP + FP
100
+ classAcc = np.diag(self.confusionMatrix) / (self.confusionMatrix.sum(axis=0) + 1e-12)
101
+ return classAcc
102
+
103
+ def meanPixelAccuracy(self):
104
+ classAcc = self.classPixelAccuracy()
105
+ meanAcc = np.nanmean(classAcc)
106
+ return meanAcc
107
+
108
+ def meanIntersectionOverUnion(self):
109
+ # Intersection = TP Union = TP + FP + FN
110
+ # IoU = TP / (TP + FP + FN)
111
+ intersection = np.diag(self.confusionMatrix)
112
+ union = np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) - np.diag(self.confusionMatrix)
113
+ IoU = intersection / union
114
+ IoU[np.isnan(IoU)] = 0
115
+ mIoU = np.nanmean(IoU)
116
+ return mIoU
117
+
118
+ def IntersectionOverUnion(self):
119
+ intersection = np.diag(self.confusionMatrix)
120
+ union = np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) - np.diag(self.confusionMatrix)
121
+ IoU = intersection / union
122
+ IoU[np.isnan(IoU)] = 0
123
+ return IoU[1]
124
+
125
+ def genConfusionMatrix(self, imgPredict, imgLabel):
126
+ # remove classes from unlabeled pixels in gt image and predict
127
+ # print(imgLabel.shape)
128
+ mask = (imgLabel >= 0) & (imgLabel < self.numClass)
129
+ label = self.numClass * imgLabel[mask] + imgPredict[mask]
130
+ count = np.bincount(label, minlength=self.numClass**2)
131
+ confusionMatrix = count.reshape(self.numClass, self.numClass)
132
+ return confusionMatrix
133
+
134
+ def Frequency_Weighted_Intersection_over_Union(self):
135
+ # FWIOU = [(TP+FN)/(TP+FP+TN+FN)] *[TP / (TP + FP + FN)]
136
+ freq = np.sum(self.confusionMatrix, axis=1) / np.sum(self.confusionMatrix)
137
+ iu = np.diag(self.confusionMatrix) / (
138
+ np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) -
139
+ np.diag(self.confusionMatrix))
140
+ FWIoU = (freq[freq > 0] * iu[freq > 0]).sum()
141
+ return FWIoU
142
+
143
+
144
+ def addBatch(self, imgPredict, imgLabel):
145
+ assert imgPredict.shape == imgLabel.shape
146
+ self.confusionMatrix += self.genConfusionMatrix(imgPredict, imgLabel)
147
+
148
+ def reset(self):
149
+ self.confusionMatrix = np.zeros((self.numClass, self.numClass))
150
+
151
+ class AverageMeter(object):
152
+ """Computes and stores the average and current value"""
153
+ def __init__(self):
154
+ self.reset()
155
+
156
+ def reset(self):
157
+ self.val = 0
158
+ self.avg = 0
159
+ self.sum = 0
160
+ self.count = 0
161
+
162
+ def update(self, val, n=1):
163
+ self.val = val
164
+ self.sum += val * n
165
+ self.count += n
166
+ self.avg = self.sum / self.count if self.count != 0 else 0
167
+
168
+ def _make_grid(nx=20, ny=20):
169
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
170
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
171
+
172
+ def split_for_trace_model(pred = None, anchor_grid = None):
173
+ z = []
174
+ st = [8,16,32]
175
+ for i in range(3):
176
+ bs, _, ny, nx = pred[i].shape
177
+ pred[i] = pred[i].view(bs, 3, 85, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
178
+ y = pred[i].sigmoid()
179
+ gr = _make_grid(nx, ny).to(pred[i].device)
180
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + gr) * st[i] # xy
181
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * anchor_grid[i] # wh
182
+ z.append(y.view(bs, -1, 85))
183
+ pred = torch.cat(z, 1)
184
+ return pred
185
+
186
+ def show_seg_result(img, result, palette=None,is_demo=False):
187
+
188
+ if palette is None:
189
+ palette = np.random.randint(
190
+ 0, 255, size=(3, 3))
191
+ palette[0] = [0, 0, 0]
192
+ palette[1] = [0, 255, 0]
193
+ palette[2] = [255, 0, 0]
194
+ palette = np.array(palette)
195
+ assert palette.shape[0] == 3 # len(classes)
196
+ assert palette.shape[1] == 3
197
+ assert len(palette.shape) == 2
198
+
199
+ if not is_demo:
200
+ color_seg = np.zeros((result.shape[0], result.shape[1], 3), dtype=np.uint8)
201
+ for label, color in enumerate(palette):
202
+ color_seg[result == label, :] = color
203
+ else:
204
+ color_area = np.zeros((result[0].shape[0], result[0].shape[1], 3), dtype=np.uint8)
205
+
206
+ color_area[result[0] == 1] = [0, 255, 0]
207
+ color_area[result[1] ==1] = [255, 0, 0]
208
+ color_seg = color_area
209
+
210
+ # convert to BGR
211
+ color_seg = color_seg[..., ::-1]
212
+ # print(color_seg.shape)
213
+ color_mask = np.mean(color_seg, 2)
214
+ img[color_mask != 0] = img[color_mask != 0] * 0.5 + color_seg[color_mask != 0] * 0.5
215
+ # img = img * 0.5 + color_seg * 0.5
216
+ #img = img.astype(np.uint8)
217
+ #img = cv2.resize(img, (1280,720), interpolation=cv2.INTER_LINEAR)
218
+ return
219
+
220
+
221
+ def increment_path(path, exist_ok=True, sep=''):
222
+ # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc.
223
+ path = Path(path) # os-agnostic
224
+ if (path.exists() and exist_ok) or (not path.exists()):
225
+ return str(path)
226
+ else:
227
+ dirs = glob.glob(f"{path}{sep}*") # similar paths
228
+ matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
229
+ i = [int(m.groups()[0]) for m in matches if m] # indices
230
+ n = max(i) + 1 if i else 2 # increment number
231
+ return f"{path}{sep}{n}" # update path
232
+
233
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
234
+ # Rescale coords (xyxy) from img1_shape to img0_shape
235
+ if ratio_pad is None: # calculate from img0_shape
236
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
237
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
238
+ else:
239
+ gain = ratio_pad[0][0]
240
+ pad = ratio_pad[1]
241
+
242
+ coords[:, [0, 2]] -= pad[0] # x padding
243
+ coords[:, [1, 3]] -= pad[1] # y padding
244
+ coords[:, :4] /= gain
245
+ clip_coords(coords, img0_shape)
246
+ return coords
247
+
248
+
249
+ def clip_coords(boxes, img_shape):
250
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
251
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
252
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
253
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
254
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
255
+
256
+ def set_logging(rank=-1):
257
+ logging.basicConfig(
258
+ format="%(message)s",
259
+ level=logging.INFO if rank in [-1, 0] else logging.WARN)
260
+
261
+ def xywh2xyxy(x):
262
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
263
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
264
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
265
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
266
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
267
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
268
+ return y
269
+
270
+ def xyxy2xywh(x):
271
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
272
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
273
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
274
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
275
+ y[:, 2] = x[:, 2] - x[:, 0] # width
276
+ y[:, 3] = x[:, 3] - x[:, 1] # height
277
+ return y
278
+
279
+ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
280
+ labels=()):
281
+ """Runs Non-Maximum Suppression (NMS) on inference results
282
+ Returns:
283
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
284
+ """
285
+
286
+ nc = prediction.shape[2] - 5 # number of classes
287
+ xc = prediction[..., 4] > conf_thres # candidates
288
+
289
+ # Settings
290
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
291
+ max_det = 300 # maximum number of detections per image
292
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
293
+ time_limit = 10.0 # seconds to quit after
294
+ redundant = True # require redundant detections
295
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
296
+ merge = False # use merge-NMS
297
+
298
+ t = time.time()
299
+ output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
300
+ for xi, x in enumerate(prediction): # image index, image inference
301
+ # Apply constraints
302
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
303
+ x = x[xc[xi]] # confidence
304
+
305
+ # Cat apriori labels if autolabelling
306
+ if labels and len(labels[xi]):
307
+ l = labels[xi]
308
+ v = torch.zeros((len(l), nc + 5), device=x.device)
309
+ v[:, :4] = l[:, 1:5] # box
310
+ v[:, 4] = 1.0 # conf
311
+ v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
312
+ x = torch.cat((x, v), 0)
313
+
314
+ # If none remain process next image
315
+ if not x.shape[0]:
316
+ continue
317
+
318
+ # Compute conf
319
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
320
+
321
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
322
+ box = xywh2xyxy(x[:, :4])
323
+
324
+ # Detections matrix nx6 (xyxy, conf, cls)
325
+ if multi_label:
326
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
327
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
328
+ else: # best class only
329
+ conf, j = x[:, 5:].max(1, keepdim=True)
330
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
331
+
332
+ # Filter by class
333
+ if classes is not None:
334
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
335
+
336
+ # Apply finite constraint
337
+ # if not torch.isfinite(x).all():
338
+ # x = x[torch.isfinite(x).all(1)]
339
+
340
+ # Check shape
341
+ n = x.shape[0] # number of boxes
342
+ if not n: # no boxes
343
+ continue
344
+ elif n > max_nms: # excess boxes
345
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
346
+
347
+ # Batched NMS
348
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
349
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
350
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
351
+ if i.shape[0] > max_det: # limit detections
352
+ i = i[:max_det]
353
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
354
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
355
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
356
+ weights = iou * scores[None] # box weights
357
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
358
+ if redundant:
359
+ i = i[iou.sum(1) > 1] # require redundancy
360
+
361
+ output[xi] = x[i]
362
+ if (time.time() - t) > time_limit:
363
+ print(f'WARNING: NMS time limit {time_limit}s exceeded')
364
+ break # time limit exceeded
365
+
366
+ return output
367
+
368
+ def box_iou(box1, box2):
369
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
370
+ """
371
+ Return intersection-over-union (Jaccard index) of boxes.
372
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
373
+ Arguments:
374
+ box1 (Tensor[N, 4])
375
+ box2 (Tensor[M, 4])
376
+ Returns:
377
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
378
+ IoU values for every element in boxes1 and boxes2
379
+ """
380
+
381
+ def box_area(box):
382
+ # box = 4xn
383
+ return (box[2] - box[0]) * (box[3] - box[1])
384
+
385
+ area1 = box_area(box1.T)
386
+ area2 = box_area(box2.T)
387
+
388
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
389
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
390
+ return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
391
+
392
+ class LoadImages: # for inference
393
+ def __init__(self, path, img_size=640, stride=32):
394
+ p = str(Path(path).absolute()) # os-agnostic absolute path
395
+ if '*' in p:
396
+ files = sorted(glob.glob(p, recursive=True)) # glob
397
+ elif os.path.isdir(p):
398
+ files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
399
+ elif os.path.isfile(p):
400
+ files = [p] # files
401
+ else:
402
+ raise Exception(f'ERROR: {p} does not exist')
403
+
404
+ img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
405
+ vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
406
+ images = [x for x in files if x.split('.')[-1].lower() in img_formats]
407
+ videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
408
+ ni, nv = len(images), len(videos)
409
+
410
+ self.img_size = img_size
411
+ self.stride = stride
412
+ self.files = images + videos
413
+ self.nf = ni + nv # number of files
414
+ self.video_flag = [False] * ni + [True] * nv
415
+ self.mode = 'image'
416
+ if any(videos):
417
+ self.new_video(videos[0]) # new video
418
+ else:
419
+ self.cap = None
420
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
421
+ f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}'
422
+
423
+ def __iter__(self):
424
+ self.count = 0
425
+ return self
426
+
427
+ def __next__(self):
428
+ if self.count == self.nf:
429
+ raise StopIteration
430
+ path = self.files[self.count]
431
+
432
+ if self.video_flag[self.count]:
433
+ # Read video
434
+ self.mode = 'video'
435
+ ret_val, img0 = self.cap.read()
436
+ if not ret_val:
437
+ self.count += 1
438
+ self.cap.release()
439
+ if self.count == self.nf: # last video
440
+ raise StopIteration
441
+ else:
442
+ path = self.files[self.count]
443
+ self.new_video(path)
444
+ ret_val, img0 = self.cap.read()
445
+
446
+ self.frame += 1
447
+ print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='')
448
+
449
+ else:
450
+ # Read image
451
+ self.count += 1
452
+ img0 = cv2.imread(path) # BGR
453
+ assert img0 is not None, 'Image Not Found ' + path
454
+ #print(f'image {self.count}/{self.nf} {path}: ', end='')
455
+
456
+ # Padded resize
457
+ img0 = cv2.resize(img0, (1280,720), interpolation=cv2.INTER_LINEAR)
458
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
459
+
460
+ # Convert
461
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
462
+ img = np.ascontiguousarray(img)
463
+
464
+ return path, img, img0, self.cap
465
+
466
+ def new_video(self, path):
467
+ self.frame = 0
468
+ self.cap = cv2.VideoCapture(path)
469
+ self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
470
+
471
+ def __len__(self):
472
+ return self.nf # number of files
473
+
474
+ def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
475
+ # Resize and pad image while meeting stride-multiple constraints
476
+ shape = img.shape[:2] # current shape [height, width]
477
+ if isinstance(new_shape, int):
478
+ new_shape = (new_shape, new_shape)
479
+ #print(sem_img.shape)
480
+ # Scale ratio (new / old)
481
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
482
+
483
+ if not scaleup: # only scale down, do not scale up (for better test mAP)
484
+ r = min(r, 1.0)
485
+
486
+ # Compute padding
487
+ ratio = r, r # width, height ratios
488
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
489
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
490
+ if auto: # minimum rectangle
491
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
492
+ elif scaleFill: # stretch
493
+ dw, dh = 0.0, 0.0
494
+ new_unpad = (new_shape[1], new_shape[0])
495
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
496
+
497
+ dw /= 2 # divide padding into 2 sides
498
+ dh /= 2
499
+
500
+ if shape[::-1] != new_unpad: # resize
501
+ img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
502
+
503
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
504
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
505
+
506
+ img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
507
+
508
+ return img, ratio, (dw, dh)
509
+
510
+ def driving_area_mask(seg = None):
511
+ da_predict = seg[:, :, 12:372,:]
512
+ da_seg_mask = torch.nn.functional.interpolate(da_predict, scale_factor=2, mode='bilinear')
513
+ _, da_seg_mask = torch.max(da_seg_mask, 1)
514
+ da_seg_mask = da_seg_mask.int().squeeze().cpu().numpy()
515
+ return da_seg_mask
516
+
517
+ def lane_line_mask(ll = None):
518
+ ll_predict = ll[:, :, 12:372,:]
519
+ ll_seg_mask = torch.nn.functional.interpolate(ll_predict, scale_factor=2, mode='bilinear')
520
+ ll_seg_mask = torch.round(ll_seg_mask).squeeze(1)
521
+ ll_seg_mask = ll_seg_mask.int().squeeze().cpu().numpy()
522
+ return ll_seg_mask