Megatron17 commited on
Commit
82e800c
1 Parent(s): 227bb46

Upload 3 files

Browse files
Files changed (3) hide show
  1. config.py +58 -0
  2. model.py +161 -0
  3. utils.py +184 -0
config.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import albumentations as A
2
+ import cv2
3
+ import torch
4
+
5
+ from albumentations.pytorch import ToTensorV2
6
+
7
+
8
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
9
+
10
+
11
+ IMAGE_SIZE = 416
12
+ transforms = A.Compose(
13
+ [
14
+ A.LongestMaxSize(max_size=IMAGE_SIZE),
15
+ A.PadIfNeeded(
16
+ min_height=IMAGE_SIZE, min_width=IMAGE_SIZE, border_mode=cv2.BORDER_CONSTANT
17
+ ),
18
+ A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255,),
19
+ ToTensorV2(),
20
+ ],
21
+ )
22
+
23
+
24
+ ANCHORS = [
25
+ [(0.28, 0.22), (0.38, 0.48), (0.9, 0.78)],
26
+ [(0.07, 0.15), (0.15, 0.11), (0.14, 0.29)],
27
+ [(0.02, 0.03), (0.04, 0.07), (0.08, 0.06)],
28
+ ] # Note these have been rescaled to be between [0, 1]
29
+
30
+ S = [IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8]
31
+
32
+ scaled_anchors = (
33
+ torch.tensor(ANCHORS)
34
+ * torch.tensor(S).unsqueeze(1).unsqueeze(1).repeat(1, 3, 2)
35
+ ).to(DEVICE)
36
+
37
+ PASCAL_CLASSES = [
38
+ "aeroplane",
39
+ "bicycle",
40
+ "bird",
41
+ "boat",
42
+ "bottle",
43
+ "bus",
44
+ "car",
45
+ "cat",
46
+ "chair",
47
+ "cow",
48
+ "diningtable",
49
+ "dog",
50
+ "horse",
51
+ "motorbike",
52
+ "person",
53
+ "pottedplant",
54
+ "sheep",
55
+ "sofa",
56
+ "train",
57
+ "tvmonitor"
58
+ ]
model.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import pytorch_lightning as pl
4
+ import config as cfg
5
+
6
+ """
7
+ Information about architecture config:
8
+ Tuple is structured by (filters, kernel_size, stride)
9
+ Every conv is a same convolution.
10
+ List is structured by "B" indicating a residual block followed by the number of repeats
11
+ "S" is for scale prediction block and computing the yolo loss
12
+ "U" is for upsampling the feature map and concatenating with a previous layer
13
+ """
14
+ config = [
15
+ (32, 3, 1),
16
+ (64, 3, 2),
17
+ ["B", 1],
18
+ (128, 3, 2),
19
+ ["B", 2],
20
+ (256, 3, 2),
21
+ ["B", 8],
22
+ (512, 3, 2),
23
+ ["B", 8],
24
+ (1024, 3, 2),
25
+ ["B", 4], # To this point is Darknet-53
26
+ (512, 1, 1),
27
+ (1024, 3, 1),
28
+ "S",
29
+ (256, 1, 1),
30
+ "U",
31
+ (256, 1, 1),
32
+ (512, 3, 1),
33
+ "S",
34
+ (128, 1, 1),
35
+ "U",
36
+ (128, 1, 1),
37
+ (256, 3, 1),
38
+ "S",
39
+ ]
40
+
41
+ class CNNBlock(nn.Module):
42
+ def __init__(self, in_channels, out_channels, bn_act=True, **kwargs):
43
+ super().__init__()
44
+ self.conv = nn.Conv2d(in_channels, out_channels, bias=not bn_act, **kwargs)
45
+ self.bn = nn.BatchNorm2d(out_channels)
46
+ self.leaky = nn.LeakyReLU(0.1)
47
+ self.use_bn_act = bn_act
48
+
49
+ def forward(self, x):
50
+ if self.use_bn_act:
51
+ return self.leaky(self.bn(self.conv(x)))
52
+ else:
53
+ return self.conv(x)
54
+
55
+
56
+ class ResidualBlock(nn.Module):
57
+ def __init__(self, channels, use_residual=True, num_repeats=1):
58
+ super().__init__()
59
+ self.layers = nn.ModuleList()
60
+ for repeat in range(num_repeats):
61
+ self.layers += [
62
+ nn.Sequential(
63
+ CNNBlock(channels, channels // 2, kernel_size=1),
64
+ CNNBlock(channels // 2, channels, kernel_size=3, padding=1),
65
+ )
66
+ ]
67
+
68
+ self.use_residual = use_residual
69
+ self.num_repeats = num_repeats
70
+
71
+ def forward(self, x):
72
+ for layer in self.layers:
73
+ if self.use_residual:
74
+ x = x + layer(x)
75
+ else:
76
+ x = layer(x)
77
+
78
+ return x
79
+
80
+
81
+ class ScalePrediction(nn.Module):
82
+ def __init__(self, in_channels, num_classes):
83
+ super().__init__()
84
+ self.pred = nn.Sequential(
85
+ CNNBlock(in_channels, 2 * in_channels, kernel_size=3, padding=1),
86
+ CNNBlock(
87
+ 2 * in_channels, (num_classes + 5) * 3, bn_act=False, kernel_size=1
88
+ ),
89
+ )
90
+ self.num_classes = num_classes
91
+
92
+ def forward(self, x):
93
+ return (
94
+ self.pred(x)
95
+ .reshape(x.shape[0], 3, self.num_classes + 5, x.shape[2], x.shape[3])
96
+ .permute(0, 1, 3, 4, 2)
97
+ )
98
+
99
+
100
+ class Lightning_YOLO(pl.LightningModule):
101
+ def __init__(self, in_channels=3, num_classes=20):
102
+ super().__init__()
103
+ self.num_classes = num_classes
104
+ self.in_channels = in_channels
105
+ self.layers = self._create_conv_layers()
106
+
107
+ def forward(self, x):
108
+ outputs = [] # for each scale
109
+ route_connections = []
110
+ for layer in self.layers:
111
+ if isinstance(layer, ScalePrediction):
112
+ outputs.append(layer(x))
113
+ continue
114
+
115
+ x = layer(x)
116
+
117
+ if isinstance(layer, ResidualBlock) and layer.num_repeats == 8:
118
+ route_connections.append(x)
119
+
120
+ elif isinstance(layer, nn.Upsample):
121
+ x = torch.cat([x, route_connections[-1]], dim=1)
122
+ route_connections.pop()
123
+
124
+ return outputs
125
+
126
+ def _create_conv_layers(self):
127
+ layers = nn.ModuleList()
128
+ in_channels = self.in_channels
129
+
130
+ for module in config:
131
+ if isinstance(module, tuple):
132
+ out_channels, kernel_size, stride = module
133
+ layers.append(
134
+ CNNBlock(
135
+ in_channels,
136
+ out_channels,
137
+ kernel_size=kernel_size,
138
+ stride=stride,
139
+ padding=1 if kernel_size == 3 else 0,
140
+ )
141
+ )
142
+ in_channels = out_channels
143
+
144
+ elif isinstance(module, list):
145
+ num_repeats = module[1]
146
+ layers.append(ResidualBlock(in_channels, num_repeats=num_repeats,))
147
+
148
+ elif isinstance(module, str):
149
+ if module == "S":
150
+ layers += [
151
+ ResidualBlock(in_channels, use_residual=False, num_repeats=1),
152
+ CNNBlock(in_channels, in_channels // 2, kernel_size=1),
153
+ ScalePrediction(in_channels // 2, num_classes=self.num_classes),
154
+ ]
155
+ in_channels = in_channels // 2
156
+
157
+ elif module == "U":
158
+ layers.append(nn.Upsample(scale_factor=2),)
159
+ in_channels = in_channels * 3
160
+
161
+ return layers
utils.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import torch
3
+ import numpy as np
4
+ import cv2
5
+ import random
6
+
7
+ from pytorch_grad_cam.base_cam import BaseCAM
8
+ from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
9
+ from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
10
+
11
+
12
+ def cells_to_bboxes(predictions, anchors, S, is_preds=True):
13
+ """
14
+ Scales the predictions coming from the model to
15
+ be relative to the entire image such that they for example later
16
+ can be plotted or.
17
+ INPUT:
18
+ predictions: tensor of size (N, 3, S, S, num_classes+5)
19
+ anchors: the anchors used for the predictions
20
+ S: the number of cells the image is divided in on the width (and height)
21
+ is_preds: whether the input is predictions or the true bounding boxes
22
+ OUTPUT:
23
+ converted_bboxes: the converted boxes of sizes (N, num_anchors, S, S, 1+5) with class index,
24
+ object score, bounding box coordinates
25
+ """
26
+ BATCH_SIZE = predictions.shape[0]
27
+ num_anchors = len(anchors)
28
+ box_predictions = predictions[..., 1:5]
29
+ if is_preds:
30
+ anchors = anchors.reshape(1, len(anchors), 1, 1, 2)
31
+ box_predictions[..., 0:2] = torch.sigmoid(box_predictions[..., 0:2])
32
+ box_predictions[..., 2:] = torch.exp(box_predictions[..., 2:]) * anchors
33
+ scores = torch.sigmoid(predictions[..., 0:1])
34
+ best_class = torch.argmax(predictions[..., 5:], dim=-1).unsqueeze(-1)
35
+ else:
36
+ scores = predictions[..., 0:1]
37
+ best_class = predictions[..., 5:6]
38
+
39
+ cell_indices = (
40
+ torch.arange(S)
41
+ .repeat(predictions.shape[0], 3, S, 1)
42
+ .unsqueeze(-1)
43
+ .to(predictions.device)
44
+ )
45
+ x = 1 / S * (box_predictions[..., 0:1] + cell_indices)
46
+ y = 1 / S * (box_predictions[..., 1:2] + cell_indices.permute(0, 1, 3, 2, 4))
47
+ w_h = 1 / S * box_predictions[..., 2:4]
48
+ converted_bboxes = torch.cat((best_class, scores, x, y, w_h), dim=-1).reshape(BATCH_SIZE, num_anchors * S * S, 6)
49
+ return converted_bboxes.tolist()
50
+
51
+
52
+ def intersection_over_union(boxes_preds, boxes_labels, box_format="midpoint"):
53
+ """
54
+ Video explanation of this function:
55
+ https://youtu.be/XXYG5ZWtjj0
56
+ This function calculates intersection over union (iou) given pred boxes
57
+ and target boxes.
58
+ Parameters:
59
+ boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4)
60
+ boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4)
61
+ box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2)
62
+ Returns:
63
+ tensor: Intersection over union for all examples
64
+ """
65
+
66
+ if box_format == "midpoint":
67
+ box1_x1 = boxes_preds[..., 0:1] - boxes_preds[..., 2:3] / 2
68
+ box1_y1 = boxes_preds[..., 1:2] - boxes_preds[..., 3:4] / 2
69
+ box1_x2 = boxes_preds[..., 0:1] + boxes_preds[..., 2:3] / 2
70
+ box1_y2 = boxes_preds[..., 1:2] + boxes_preds[..., 3:4] / 2
71
+ box2_x1 = boxes_labels[..., 0:1] - boxes_labels[..., 2:3] / 2
72
+ box2_y1 = boxes_labels[..., 1:2] - boxes_labels[..., 3:4] / 2
73
+ box2_x2 = boxes_labels[..., 0:1] + boxes_labels[..., 2:3] / 2
74
+ box2_y2 = boxes_labels[..., 1:2] + boxes_labels[..., 3:4] / 2
75
+
76
+ if box_format == "corners":
77
+ box1_x1 = boxes_preds[..., 0:1]
78
+ box1_y1 = boxes_preds[..., 1:2]
79
+ box1_x2 = boxes_preds[..., 2:3]
80
+ box1_y2 = boxes_preds[..., 3:4]
81
+ box2_x1 = boxes_labels[..., 0:1]
82
+ box2_y1 = boxes_labels[..., 1:2]
83
+ box2_x2 = boxes_labels[..., 2:3]
84
+ box2_y2 = boxes_labels[..., 3:4]
85
+
86
+ x1 = torch.max(box1_x1, box2_x1)
87
+ y1 = torch.max(box1_y1, box2_y1)
88
+ x2 = torch.min(box1_x2, box2_x2)
89
+ y2 = torch.min(box1_y2, box2_y2)
90
+
91
+ intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0)
92
+ box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1))
93
+ box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1))
94
+
95
+ return intersection / (box1_area + box2_area - intersection + 1e-6)
96
+
97
+
98
+ def non_max_suppression(bboxes, iou_threshold, threshold, box_format="corners"):
99
+ """
100
+ Video explanation of this function:
101
+ https://youtu.be/YDkjWEN8jNA
102
+ Does Non Max Suppression given bboxes
103
+ Parameters:
104
+ bboxes (list): list of lists containing all bboxes with each bboxes
105
+ specified as [class_pred, prob_score, x1, y1, x2, y2]
106
+ iou_threshold (float): threshold where predicted bboxes is correct
107
+ threshold (float): threshold to remove predicted bboxes (independent of IoU)
108
+ box_format (str): "midpoint" or "corners" used to specify bboxes
109
+ Returns:
110
+ list: bboxes after performing NMS given a specific IoU threshold
111
+ """
112
+
113
+ assert type(bboxes) == list
114
+
115
+ bboxes = [box for box in bboxes if box[1] > threshold]
116
+ bboxes = sorted(bboxes, key=lambda x: x[1], reverse=True)
117
+ bboxes_after_nms = []
118
+
119
+ while bboxes:
120
+ chosen_box = bboxes.pop(0)
121
+
122
+ bboxes = [
123
+ box
124
+ for box in bboxes
125
+ if box[0] != chosen_box[0]
126
+ or intersection_over_union(
127
+ torch.tensor(chosen_box[2:]),
128
+ torch.tensor(box[2:]),
129
+ box_format=box_format,
130
+ )
131
+ < iou_threshold
132
+ ]
133
+
134
+ bboxes_after_nms.append(chosen_box)
135
+
136
+ return bboxes_after_nms
137
+
138
+
139
+ def draw_bounding_boxes(image, boxes, class_labels):
140
+
141
+ colors = [[random.randint(0, 255) for _ in range(3)] for name in class_labels]
142
+
143
+ im = np.array(image)
144
+ height, width, _ = im.shape
145
+ bbox_thick = int(0.6 * (height + width) / 600)
146
+
147
+ # Create a Rectangle patch
148
+ for box in boxes:
149
+ assert len(box) == 6, "box should contain class pred, confidence, x, y, width, height"
150
+ class_pred = box[0]
151
+ conf = box[1]
152
+ box = box[2:]
153
+ upper_left_x = box[0] - box[2] / 2
154
+ upper_left_y = box[1] - box[3] / 2
155
+
156
+ x1 = int(upper_left_x * width)
157
+ y1 = int(upper_left_y * height)
158
+
159
+ x2 = x1 + int(box[2] * width)
160
+ y2 = y1 + int(box[3] * height)
161
+
162
+ cv2.rectangle(
163
+ image,
164
+ (x1, y1), (x2, y2),
165
+ color=colors[int(class_pred)],
166
+ thickness=bbox_thick
167
+ )
168
+ text = f"{class_labels[int(class_pred)]}: {conf:.2f}"
169
+ t_size = cv2.getTextSize(text, 0, 0.7, thickness=bbox_thick // 2)[0]
170
+ c3 = (x1 + t_size[0], y1 - t_size[1] - 3)
171
+
172
+ cv2.rectangle(image, (x1, y1), c3, colors[int(class_pred)], -1)
173
+ cv2.putText(
174
+ image,
175
+ text,
176
+ (x1, y1 - 2),
177
+ cv2.FONT_HERSHEY_SIMPLEX,
178
+ 0.7,
179
+ (0, 0, 0),
180
+ bbox_thick // 2,
181
+ lineType=cv2.LINE_AA,
182
+ )
183
+
184
+ return image