anh1811 commited on
Commit
8d4bf19
·
1 Parent(s): 9f2557d

Upload 16 files

Browse files
2007_base_10_10_mAP_10_10.pth (1).tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f2cf61c8a0685a211ed58722fadcdc86355a6222ee542bbd585d06ac7d2d4bc
3
+ size 739451088
2007_base_15_5_mAP_15_5.pth (1).tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:034c0239cf38e567291becb37e70a7771d13d461a38aeddffe75b7ea008df37a
3
+ size 739772750
2007_base_19_1_mAP_19_1.pth (1).tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43ceed829c69943cb1aab99dc5303b321ba1ffc864a11d9fcb802f8baa21e668
3
+ size 740030798
2007_finetune_10_10_mAP_10_10.pth.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0863385a77abf7d1c68c1092bf5b5a8c93c8a09830da13decc006934b5736304
3
+ size 739675028
2007_finetune_15_5_mAP_15_5.pth.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7aa374db868c2163fd857831ed83d92e975c820e47c40682c43eb7663a6d407
3
+ size 739888146
2007_finetune_19_1_mAP_19_1.pth (1).tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84e42744ffd5b084cba987618bfbf44d139f1ab1a8c32ab936bfa57a9e7e809a
3
+ size 740060242
2007_finetune_19_1_mAP_19_1.pth.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91c85c59ddbdf40fe36ae6c59ee02a0751a03f7cce22bf426c64c6c8042573fa
3
+ size 740060242
2007_image_store_base_16_5.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5eda9ef842bb084d651296c5b7345060ecf166bcab17e39ead080204a43f15ef
3
+ size 21679
2007_task2_10_10_mAP_10_10.pth (2) (1).tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e49103fe59a4101cb9a43b56d7c1a8263ef947665ed470b5f88e534d79759d6d
3
+ size 739671601
2007_task2_15_5_mAP_15_5.pth (3) (1).tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f890ee29b5e4367474b66079572a5f0558587db5e77d81d80d0deb182c72d7c
3
+ size 739884783
2007_task2_19_1_mAP_19_1.pth (3) (1).tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4a92093f22e10382a2da0fc38f94e5200d4d6af2ea0feac6dc2593a478e7b31
3
+ size 740056815
app.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ # import config
3
+ import albumentations as A
4
+ from albumentations.pytorch import ToTensorV2
5
+ import torch
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ import matplotlib.patches as patches
9
+ import math
10
+ from PIL import Image
11
+ # import wandb
12
+ from model import YOLOv3
13
+ import cv2
14
+
15
+ IMAGE_SIZE = 416
16
+ ANCHORS = [
17
+ [(0.28, 0.22), (0.38, 0.48), (0.9, 0.78)],
18
+ [(0.07, 0.15), (0.15, 0.11), (0.14, 0.29)],
19
+ [(0.02, 0.03), (0.04, 0.07), (0.08, 0.06)],
20
+ ]
21
+ S = [IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8]
22
+
23
+ infer_transforms = A.Compose(
24
+ [
25
+ A.LongestMaxSize(max_size=IMAGE_SIZE),
26
+ A.PadIfNeeded(
27
+ min_height=IMAGE_SIZE, min_width=IMAGE_SIZE, border_mode=cv2.BORDER_CONSTANT
28
+ ),
29
+ A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255,),
30
+ ToTensorV2(),
31
+ ]
32
+ )
33
+
34
+ def cells_to_bboxes(predictions, anchors, S, is_preds=True):
35
+ """
36
+ Scales the predictions coming from the model to
37
+ be relative to the entire image such that they for example later
38
+ can be plotted or.
39
+ INPUT:
40
+ predictions: tensor of size (N, 3, S, S, num_classes+5)
41
+ anchors: the anchors used for the predictions
42
+ S: the number of cells the image is divided in on the width (and height)
43
+ is_preds: whether the input is predictions or the true bounding boxes
44
+ OUTPUT:
45
+ converted_bboxes: the converted boxes of sizes (N, num_anchors, S, S, 1+5) with class index,
46
+ object score, bounding box coordinates
47
+ """
48
+ BATCH_SIZE = predictions.shape[0]
49
+ num_anchors = len(anchors)
50
+ box_predictions = predictions[..., 1:5]
51
+ if is_preds:
52
+ anchors = anchors.reshape(1, len(anchors), 1, 1, 2)
53
+ box_predictions[..., 0:2] = torch.sigmoid(box_predictions[..., 0:2])
54
+ box_predictions[..., 2:] = torch.exp(box_predictions[..., 2:]) * anchors
55
+ scores = torch.sigmoid(predictions[..., 0:1])
56
+ best_class = torch.argmax(predictions[..., 5:], dim=-1).unsqueeze(-1)
57
+ else:
58
+ scores = predictions[..., 0:1]
59
+ best_class = predictions[..., 5:6]
60
+
61
+ cell_indices = (
62
+ torch.arange(S)
63
+ .repeat(predictions.shape[0], 3, S, 1)
64
+ .unsqueeze(-1)
65
+ .to(predictions.device)
66
+ )
67
+ x = 1 / S * (box_predictions[..., 0:1] + cell_indices)
68
+ y = 1 / S * (box_predictions[..., 1:2] + cell_indices.permute(0, 1, 3, 2, 4))
69
+ w_h = 1 / S * box_predictions[..., 2:4]
70
+ converted_bboxes = torch.cat((best_class, scores, x, y, w_h), dim=-1).reshape(BATCH_SIZE, num_anchors * S * S, 6)
71
+ return converted_bboxes.tolist()
72
+
73
+ def non_max_suppression(bboxes, iou_threshold, threshold, box_format="corners"):
74
+ """
75
+ Video explanation of this function:
76
+ https://youtu.be/YDkjWEN8jNA
77
+
78
+ Does Non Max Suppression given bboxes
79
+
80
+ Parameters:
81
+ bboxes (list): list of lists containing all bboxes with each bboxes
82
+ specified as [class_pred, prob_score, x1, y1, x2, y2]
83
+ iou_threshold (float): threshold where predicted bboxes is correct
84
+ threshold (float): threshold to remove predicted bboxes (independent of IoU)
85
+ box_format (str): "midpoint" or "corners" used to specify bboxes
86
+
87
+ Returns:
88
+ list: bboxes after performing NMS given a specific IoU threshold
89
+ """
90
+
91
+ assert type(bboxes) == list
92
+
93
+ bboxes = [box for box in bboxes if box[1] > threshold]
94
+ bboxes = sorted(bboxes, key=lambda x: x[1], reverse=True)
95
+ bboxes_after_nms = []
96
+
97
+ while bboxes:
98
+ chosen_box = bboxes.pop(0)
99
+
100
+ bboxes = [
101
+ box
102
+ for box in bboxes
103
+ if box[0] != chosen_box[0]
104
+ or intersection_over_union(
105
+ torch.tensor(chosen_box[2:]),
106
+ torch.tensor(box[2:]),
107
+ box_format=box_format,
108
+ )
109
+ < iou_threshold
110
+ ]
111
+
112
+ bboxes_after_nms.append(chosen_box)
113
+
114
+ return bboxes_after_nms
115
+
116
+ def intersection_over_union(boxes_preds, boxes_labels, box_format="midpoint", GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
117
+ """
118
+ Video explanation of this function:
119
+ https://youtu.be/XXYG5ZWtjj0
120
+
121
+ This function calculates intersection over union (iou) given pred boxes
122
+ and target boxes.
123
+
124
+ Parameters:
125
+ boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4)
126
+ boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4)
127
+ box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2)
128
+
129
+ Returns:
130
+ tensor: Intersection over union for all examples
131
+ """
132
+
133
+ if box_format == "midpoint":
134
+ box1_x1 = boxes_preds[..., 0:1] - boxes_preds[..., 2:3] / 2
135
+ box1_y1 = boxes_preds[..., 1:2] - boxes_preds[..., 3:4] / 2
136
+ box1_x2 = boxes_preds[..., 0:1] + boxes_preds[..., 2:3] / 2
137
+ box1_y2 = boxes_preds[..., 1:2] + boxes_preds[..., 3:4] / 2
138
+ box2_x1 = boxes_labels[..., 0:1] - boxes_labels[..., 2:3] / 2
139
+ box2_y1 = boxes_labels[..., 1:2] - boxes_labels[..., 3:4] / 2
140
+ box2_x2 = boxes_labels[..., 0:1] + boxes_labels[..., 2:3] / 2
141
+ box2_y2 = boxes_labels[..., 1:2] + boxes_labels[..., 3:4] / 2
142
+ w1 = boxes_preds[..., 2:3]
143
+ h1 = boxes_preds[..., 3:4]
144
+ w2 = boxes_labels[..., 2:3]
145
+ h2 = boxes_labels[..., 3:4]
146
+ if box_format == "corners":
147
+ box1_x1 = boxes_preds[..., 0:1]
148
+ box1_y1 = boxes_preds[..., 1:2]
149
+ box1_x2 = boxes_preds[..., 2:3]
150
+ box1_y2 = boxes_preds[..., 3:4]
151
+ box2_x1 = boxes_labels[..., 0:1]
152
+ box2_y1 = boxes_labels[..., 1:2]
153
+ box2_x2 = boxes_labels[..., 2:3]
154
+ box2_y2 = boxes_labels[..., 3:4]
155
+
156
+ x1 = torch.max(box1_x1, box2_x1)
157
+ y1 = torch.max(box1_y1, box2_y1)
158
+ x2 = torch.min(box1_x2, box2_x2)
159
+ y2 = torch.min(box1_y2, box2_y2)
160
+
161
+ intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0)
162
+ box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1))
163
+ box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1))
164
+ iou = intersection / (box1_area + box2_area - intersection)
165
+ if CIoU or DIoU or GIoU:
166
+ cw = box1_x2.maximum(box2_x2) - box1_x1.minimum(box2_x1) # convex (smallest enclosing box) width
167
+ ch = box1_y2.maximum(box2_y2) - box1_y1.minimum(box2_y1) # convex height
168
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
169
+ c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
170
+ rho2 = ((box2_x1 + box2_x2 - box1_x1 - box1_x2) ** 2 + (box2_y1 + box2_y2 - box1_y1 - box1_y2) ** 2) / 4 # center dist ** 2
171
+ if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
172
+ v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
173
+ with torch.no_grad():
174
+ alpha = v / (v - iou + (1 + eps))
175
+ return iou - (rho2 / c2 + v * alpha) # CIoU
176
+ return iou - rho2 / c2 # DIoU
177
+ c_area = cw * ch + eps # convex area
178
+ return iou - (c_area - intersection) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
179
+ return intersection / (box1_area + box2_area - intersection + 1e-6)
180
+
181
+ def resize_box(box, origin_dims, in_dims):
182
+ # amount of padding
183
+ h_ori, w_ori = origin_dims[0], origin_dims[1]
184
+ print(h_ori, w_ori)
185
+ padding_height = max(w_ori - h_ori, 0) * in_dims/w_ori
186
+ padding_width = max(h_ori - w_ori, 0) * in_dims/h_ori
187
+
188
+ #picture size after remove pad
189
+ h_new = in_dims - padding_height
190
+ w_new = in_dims - padding_width
191
+
192
+ # resize box
193
+ box[0] = (box[0] - padding_width//2)* w_ori/w_new
194
+ box[1] = (box[1] - padding_height//2)* h_ori/h_new
195
+ box[2] = (box[2] - padding_width//2)* w_ori/w_new
196
+ box[3] = (box[3] - padding_height//2)* h_ori/h_new
197
+
198
+ return box
199
+
200
+ def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):
201
+ # Rescale boxes (xyxy) from img1_shape to img0_shape
202
+ if ratio_pad is None: # calculate from img0_shape
203
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
204
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
205
+ else:
206
+ gain = ratio_pad[0][0]
207
+ pad = ratio_pad[1]
208
+
209
+ boxes[..., [0, 2]] -= pad[0] # x padding
210
+ boxes[..., [1, 3]] -= pad[1] # y padding
211
+ boxes[..., :4] /= gain
212
+ clip_boxes(boxes, img0_shape)
213
+ return boxes
214
+
215
+ def clip_boxes(boxes, shape):
216
+ # Clip boxes (xyxy) to image shape (height, width)
217
+ if isinstance(boxes, torch.Tensor): # faster individually
218
+ boxes[..., 0].clamp_(0, shape[1]) # x1
219
+ boxes[..., 1].clamp_(0, shape[0]) # y1
220
+ boxes[..., 2].clamp_(0, shape[1]) # x2
221
+ boxes[..., 3].clamp_(0, shape[0]) # y2
222
+ else: # np.array (faster grouped)
223
+ boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, shape[1]) # x1, x2
224
+ boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, shape[0]) # y1, y2
225
+
226
+
227
+ def plot_image(image, boxes, image_ori=None):
228
+ import pickle as pkl
229
+ """Plots predicted bounding boxes on the image"""
230
+ # cmap = plt.get_cmap("tab20b")
231
+ class_labels = [
232
+ "aeroplane",
233
+ "bicycle",
234
+ "bird",
235
+ "boat",
236
+ "bottle",
237
+ "bus",
238
+ "car",
239
+ "cat",
240
+ "chair",
241
+ "cow",
242
+ "diningtable",
243
+ "dog",
244
+ "horse",
245
+ "motorbike",
246
+ "person",
247
+ "pottedplant",
248
+ "sheep",
249
+ "sofa",
250
+ "train",
251
+ "tvmonitor"
252
+ ]
253
+ colors = pkl.load(open("pallete", "rb"))
254
+ im = np.array(image)
255
+ height, width, _ = im.shape
256
+
257
+ # Draw bounding boxes on the image
258
+ for box in boxes:
259
+ assert len(box) == 6, "box should contain class pred, confidence, x, y, width, height"
260
+ class_pred = box[0]
261
+ conf = box[1]
262
+ box = box[2:]
263
+ box_clone = box.copy()
264
+ box[0] = max(box_clone[0] - box_clone[2] / 2, 0.) * width
265
+ box[1] = max(box_clone[1] - box_clone[3] / 2, 0.) * height
266
+ box[2] = min(box_clone[0] + box_clone[2] / 2, 1.) * width
267
+ box[3] = min(box_clone[1] + box_clone[3] / 2, 1.) * height
268
+ box = scale_boxes((height, width), torch.tensor(box), image_ori.shape[:2])
269
+ h_o, w_o, _ = image_ori.shape
270
+ color = colors[int(class_pred)]
271
+ # print(color)
272
+
273
+ # Draw rectangle
274
+ cv2.rectangle(image_ori, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), color, 2)
275
+ label = class_labels[int(class_pred)]
276
+ text = f"{label}: {conf:.2f}"
277
+ cv2.putText(image_ori, text, (int(box[0]), int(box[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
278
+
279
+ return image_ori
280
+ # cv2.imwrite("test.png", image_ori)
281
+
282
+ def infer(model, img, thresh, iou_thresh, anchors):
283
+ model.eval()
284
+ image = np.array(img)
285
+ image_copy = image.copy()
286
+ # image = image[np.newaxis, :]
287
+ augmentations = infer_transforms(image=image)
288
+ x = augmentations["image"]
289
+ # x = x.to("cuda")
290
+ x = torch.reshape(x, [1,3,416,416])
291
+ # print(x.shape)
292
+ with torch.no_grad():
293
+ out = model(x)
294
+ bboxes = [[] for _ in range(x.shape[0])]
295
+ for i in range(3):
296
+ batch_size, A, S, _, _ = out[i].shape
297
+ anchor = anchors[i]
298
+ boxes_scale_i = cells_to_bboxes(
299
+ out[i], anchor, S=S, is_preds=True
300
+ )
301
+ for idx, (box) in enumerate(boxes_scale_i):
302
+ bboxes[idx] += box
303
+
304
+ for i in range(batch_size):
305
+ nms_boxes = non_max_suppression(
306
+ bboxes[i], iou_threshold=iou_thresh, threshold=thresh, box_format="midpoint",
307
+ )
308
+ img = plot_image(x[i].permute(1,2,0).detach().cpu(), nms_boxes, image_copy)
309
+ return img
310
+
311
+ scene = st.radio(
312
+ "Chọn bối cảnh",
313
+ ('19->20', '15->20', '10->20'))
314
+ # scene = '19->20'
315
+
316
+ # task = st.radio(
317
+ # "Chọn nhiệm vụ",
318
+ # ('task1', 'task2', 'finetune'))
319
+
320
+ all = 20
321
+
322
+ if scene == '19->20':
323
+ base = 19
324
+ new = all - base
325
+ elif scene == '15->20':
326
+ base = 15
327
+ new = all - base
328
+ else:
329
+ base = 10
330
+ new = all - base
331
+
332
+ # if task == '1.Nhiệm vụ 1':
333
+ # cls = base
334
+ # task = 'task1'
335
+ # elif task == '2. Nhiệm vụ 2 (trước tinh chỉnh)':
336
+ # cls = all
337
+ # tune = False
338
+ # else:
339
+ # cls = all
340
+ # tune = True
341
+
342
+ device = "cuda"
343
+ if not torch.cuda.is_available():
344
+ device = "cpu"
345
+
346
+ scaled_anchors = (
347
+ torch.tensor(ANCHORS)
348
+ * torch.tensor(S).unsqueeze(1).unsqueeze(1).repeat(1, 3, 2)
349
+ ).to(device)
350
+
351
+
352
+ uploaded_file = st.file_uploader("Chọn hình ảnh...", type=["jpg", "jpeg", "png"])
353
+ # uploaded_file = '/home/ngocanh/Documents/final_thesis/code/dataset/10_10/base/images/test/000011.jpg'
354
+ image = Image.open(uploaded_file)
355
+ print("Thuc hien bien doi")
356
+
357
+ #task 1
358
+ file_path = f"2007_base_{base}_{new}_mAP_{base}_{new}.pth.tar"
359
+ model = YOLOv3(num_classes=base).to(device)
360
+ checkpoint = torch.load(file_path, map_location=device)
361
+ model.load_state_dict(checkpoint["state_dict"])
362
+ model.eval()
363
+ image_1 = infer(model, image, 0.5, 0.5, scaled_anchors)
364
+
365
+ #task 2
366
+ file_path = f"2007_task2_{base}_{new}_mAP_{base}_{new}.pth.tar"
367
+ model = YOLOv3(num_classes=all).to(device)
368
+ checkpoint = torch.load(file_path, map_location=device)
369
+ model.load_state_dict(checkpoint["state_dict"])
370
+ model.eval()
371
+ image_2 = infer(model, image, 0.5, 0.5, scaled_anchors)
372
+
373
+ #ft
374
+ file_path = f"2007_finetune_{base}_{new}_mAP_{base}_{new}.pth.tar"
375
+ checkpoint = torch.load(file_path, map_location=device)
376
+ model.load_state_dict(checkpoint["state_dict"])
377
+ model.eval()
378
+ image_3 = infer(model, image, 0.5, 0.5, scaled_anchors)
379
+ # Streamlit App
380
+ # Widget tải lên file ảnh
381
+
382
+ # note = Image.open("note.png")
383
+ # st.image(note, width=150)
384
+
385
+
386
+ col1, col2, col3, col4 = st.columns(4)
387
+ with col1:
388
+ st.image(image, caption="Ảnh đầu vào", use_column_width=True)
389
+ with col2:
390
+ st.image(image_1, caption="Kết quả task 1", channels="BGR", use_column_width=True)
391
+ with col3:
392
+ st.image(image_1, caption="Kết quả task 2 (no finetune)", channels="BGR", use_column_width=True)
393
+ with col4:
394
+ st.image(image_1, caption="Kết quả task 2 (finetune)", channels="BGR", use_column_width=True)
395
+
396
+
397
+ # import cv2
398
+ # image_1 = cv2.cvtColor(image_1, cv2.COLOR_BGR2RGB)
399
+ # cv2.imwrite('test.jpg',image_1)
400
+
401
+ # Hiển thị ảnh gốc
402
+
403
+ # TODO: Đưa ảnh qua mô hình để xử lý (đoán, biến đổi, ...)
404
+
405
+ # Hiển thị kết quả (ảnh sau khi qua mô hình), nếu có
406
+
407
+ # Ví dụ: Nếu bạn đã có kết quả từ mô hình (processed_img) là một PIL Image
408
+ # st.image(processed_img, caption="Processed Image", use_column_width=True)
image_store_base_15_5.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33771fc0994f203637a205e5efb5fbb76300fd5f7cf4844d7dbe71acca1dec24
3
+ size 13231
model.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of YOLOv3 architecture
3
+ """
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import config as cfg
8
+ """
9
+ Information about architecture config:
10
+ Tuple is structured by (filters, kernel_size, stride)
11
+ Every conv is a same convolution.
12
+ List is structured by "B" indicating a residual block followed by the number of repeats
13
+ "S" is for scale prediction block and computing the yolo loss
14
+ "U" is for upsampling the feature map and concatenating with a previous layer
15
+ """
16
+ config = [
17
+ (32, 3, 1),
18
+ (64, 3, 2),
19
+ ["B", 1],
20
+ (128, 3, 2),
21
+ ["B", 2],
22
+ (256, 3, 2),
23
+ ["B", 8],
24
+ (512, 3, 2),
25
+ ["B", 8],
26
+ (1024, 3, 2),
27
+ ["B", 4], # To this point is Darknet-53
28
+ (512, 1, 1),
29
+ (1024, 3, 1),
30
+ "S",
31
+ (256, 1, 1),
32
+ "U",
33
+ (256, 1, 1),
34
+ (512, 3, 1),
35
+ "S",
36
+ (128, 1, 1),
37
+ "U",
38
+ (128, 1, 1),
39
+ (256, 3, 1),
40
+ "S",
41
+ ]
42
+
43
+
44
+ class CNNBlock(nn.Module):
45
+ def __init__(self, in_channels, out_channels, bn_act=True, **kwargs):
46
+ super().__init__()
47
+ self.conv = nn.Conv2d(in_channels, out_channels, bias=not bn_act, **kwargs)
48
+ self.bn = nn.BatchNorm2d(out_channels)
49
+ self.leaky = nn.LeakyReLU(0.1)
50
+ self.use_bn_act = bn_act
51
+
52
+ def forward(self, x):
53
+ if self.use_bn_act:
54
+ return self.leaky(self.bn(self.conv(x)))
55
+ else:
56
+ return self.conv(x)
57
+
58
+
59
+ class ResidualBlock(nn.Module):
60
+ def __init__(self, channels, use_residual=True, num_repeats=1):
61
+ super().__init__()
62
+ self.layers = nn.ModuleList()
63
+ for repeat in range(num_repeats):
64
+ self.layers += [
65
+ nn.Sequential(
66
+ CNNBlock(channels, channels // 2, kernel_size=1),
67
+ CNNBlock(channels // 2, channels, kernel_size=3, padding=1),
68
+ )
69
+ ]
70
+
71
+ self.use_residual = use_residual
72
+ self.num_repeats = num_repeats
73
+
74
+ def forward(self, x):
75
+ for layer in self.layers:
76
+ if self.use_residual:
77
+ x = x + layer(x)
78
+ else:
79
+ x = layer(x)
80
+
81
+ return x
82
+
83
+
84
+ class ScalePrediction(nn.Module):
85
+ def __init__(self, in_channels, num_classes):
86
+ super().__init__()
87
+ self.pred = nn.Sequential(
88
+ CNNBlock(in_channels, 2 * in_channels, kernel_size=3, padding=1),
89
+ CNNBlock(
90
+ 2 * in_channels, (num_classes + 5) * 3, bn_act=False, kernel_size=1
91
+ ),
92
+ )
93
+ self.num_classes = num_classes
94
+
95
+ def forward(self, x):
96
+ return (
97
+ self.pred(x)
98
+ .reshape(x.shape[0], 3, -1 , x.shape[2], x.shape[3])
99
+ .permute(0, 1, 3, 4, 2)
100
+ )
101
+
102
+
103
+ class YOLOv3(nn.Module):
104
+ def __init__(self, in_channels=3, num_classes=80):
105
+ super().__init__()
106
+ self.num_classes = num_classes
107
+ self.in_channels = in_channels
108
+ self.layers = self._create_conv_layers()
109
+ self.base_model = None
110
+ self.distill_feature = cfg.DISTILL
111
+ self.warp = cfg.WARP
112
+ self.feature_store = None
113
+ self.enable_warp_train = False
114
+
115
+ def get_features(self):
116
+ return self.features
117
+
118
+ def adaptation(self, layer_id, num_class, in_feature, old_class):
119
+ with torch.no_grad():
120
+ old_weight = self.layers[layer_id].pred[1].conv.weight
121
+ old_bias = self.layers[layer_id].pred[1].conv.bias
122
+ # print(model.layers[22].pred[1])
123
+ # print(model.layers[29].pred[1])
124
+ # out_dims = cfg.BASE_CLASS + cfg.NEW_CLASS + 5
125
+ self.layers[layer_id].pred[1] = CNNBlock(in_feature, (5 + num_class) * 3, bn_act=False, kernel_size=1)
126
+ # self.layers[layer_id].pred[1].conv.weight[:(5 + old_class) * 3] = old_weight
127
+ num_fea_old = 5 + old_class
128
+ self.layers[layer_id].pred[1].conv.weight[:num_fea_old] = old_weight[:num_fea_old]
129
+ self.layers[layer_id].pred[1].conv.weight[num_fea_old + (num_class - old_class): 2*num_fea_old + (num_class - old_class)] = old_weight[num_fea_old: 2* num_fea_old]
130
+ self.layers[layer_id].pred[1].conv.weight[2* num_fea_old + 2 * (num_class - old_class): 3*num_fea_old + 2 * (num_class - old_class)] = old_weight[2* num_fea_old:]
131
+ self.layers[layer_id].pred[1].conv.bias[:num_fea_old] = old_bias[:num_fea_old]
132
+ self.layers[layer_id].pred[1].conv.bias[num_fea_old + (num_class - old_class): 2*num_fea_old + (num_class - old_class)] = old_bias[num_fea_old: 2* num_fea_old]
133
+ self.layers[layer_id].pred[1].conv.bias[2* num_fea_old + 2 * (num_class - old_class): 3*num_fea_old + 2 * (num_class - old_class)] = old_bias[2* num_fea_old:]
134
+
135
+ def forward(self, x):
136
+ outputs = [] # for each scale
137
+ route_connections = []
138
+ self.features = []
139
+ for layer in self.layers:
140
+ if isinstance(layer, ScalePrediction):
141
+ # print(x.shape)
142
+ # print(layer.pred[1].conv.weight.shape)
143
+ outputs.append(layer(x))
144
+ continue
145
+
146
+ x = layer(x)
147
+
148
+ if isinstance(layer, ResidualBlock) and layer.num_repeats == 8:
149
+ self.features.append(x)
150
+ route_connections.append(x)
151
+
152
+ elif isinstance(layer, ResidualBlock) and layer.num_repeats == 4:
153
+ self.features.append(x)
154
+
155
+ elif isinstance(layer, nn.Upsample):
156
+ x = torch.cat([x, route_connections[-1]], dim=1)
157
+ route_connections.pop()
158
+
159
+ return outputs
160
+
161
+ def _create_conv_layers(self):
162
+ layers = nn.ModuleList()
163
+ in_channels = self.in_channels
164
+
165
+ for module in config:
166
+ if isinstance(module, tuple):
167
+ out_channels, kernel_size, stride = module
168
+ layers.append(
169
+ CNNBlock(
170
+ in_channels,
171
+ out_channels,
172
+ kernel_size=kernel_size,
173
+ stride=stride,
174
+ padding=1 if kernel_size == 3 else 0,
175
+ )
176
+ )
177
+ in_channels = out_channels
178
+
179
+ elif isinstance(module, list):
180
+ num_repeats = module[1]
181
+ layers.append(ResidualBlock(in_channels, num_repeats=num_repeats,))
182
+
183
+ elif isinstance(module, str):
184
+ if module == "S":
185
+ layers += [
186
+ ResidualBlock(in_channels, use_residual=False, num_repeats=1),
187
+ CNNBlock(in_channels, in_channels // 2, kernel_size=1),
188
+ ScalePrediction(in_channels // 2, num_classes=self.num_classes),
189
+ ]
190
+ in_channels = in_channels // 2
191
+
192
+ elif module == "U":
193
+ layers.append(nn.Upsample(scale_factor=2),)
194
+ in_channels = in_channels * 3
195
+
196
+ return layers
197
+
198
+
199
+
200
+
201
+ if __name__ == "__main__":
202
+ num_classes = 19
203
+ IMAGE_SIZE = 416
204
+ model = YOLOv3(num_classes=num_classes)
205
+ # print(model)
206
+ print(model.layers[15].pred[1].conv.weight.shape)
207
+ print(model.layers[15].pred[1].conv.bias.shape)
208
+ import torch.optim as optim
209
+ optimizer = optim.Adam(
210
+ model.parameters(), lr=cfg.LEARNING_RATE, weight_decay=cfg.WEIGHT_DECAY
211
+ )
212
+ from utils import load_checkpoint
213
+ load_checkpoint(
214
+ cfg.BASE_CHECK_POINT, model, optimizer, cfg.LEARNING_RATE
215
+ )
216
+
217
+ model.adaptation(layer_id = 15, num_class = 20, in_feature = 1024, old_class = num_classes)
218
+ model.adaptation(layer_id = 22, num_class = 20, in_feature = 512, old_class = num_classes)
219
+ model.adaptation(layer_id = 29, num_class = 20, in_feature = 256, old_class = num_classes)
220
+ # layer1 =
221
+ # model.eval()
222
+ # with torch.no_grad():
223
+ # old_weight = model.layers[15].pred[1].conv.weight
224
+ # old_bias = model.layers[15].pred[1].conv.bias
225
+ # # print(model.layers[22].pred[1])
226
+ # # print(model.layers[29].pred[1])
227
+ # # out_dims = cfg.BASE_CLASS + cfg.NEW_CLASS + 5
228
+ # model.layers[15].pred[1] = CNNBlock(1024, 25 * 3, bn_act=False, kernel_size=1)
229
+ # model.layers[15].pred[1].conv.weight[:72] = old_weight
230
+ # model.layers[15].pred[1].conv.bias[:72] = old_bias
231
+ print(model.layers[15].pred[1].conv.weight.shape)
232
+ # model.layers[22].pred[1] = CNNBlock(512, out_dims * 3, kernel_size=1)
233
+ # model.layers[29].pred[1] = CNNBlock(256, out_dims * 3, kernel_size=1)
234
+ x = torch.randn((2, 3, IMAGE_SIZE, IMAGE_SIZE))
235
+ out = model(x)
236
+ # assert model(x)[0].shape == (2, 3, IMAGE_SIZE//32, IMAGE_SIZE//32, num_classes + 5)
237
+ # assert model(x)[1].shape == (2, 3, IMAGE_SIZE//16, IMAGE_SIZE//16, num_classes + 5)
238
+ # assert model(x)[2].shape == (2, 3, IMAGE_SIZE//8, IMAGE_SIZE//8, num_classes + 5)
239
+ print("Success!")
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ numpy>=1.19.2
2
+ matplotlib>=3.3.4
3
+ torch>=1.7.1
4
+ tqdm>=4.56.0
5
+ torchvision>=0.8.2
6
+ albumentations>=0.5.2
7
+ pandas>=1.2.1
8
+ Pillow>=8.1.0