Skip to content

Commit 114465d

Browse files
committed
move boolean string to utils
1 parent c533bc2 commit 114465d

File tree

3 files changed

+38
-37
lines changed

3 files changed

+38
-37
lines changed

coco_eval.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,17 @@
2222

2323
from backbone import EfficientDetBackbone
2424
from efficientdet.utils import BBoxTransform, ClipBoxes
25-
from utils.utils import preprocess, invert_affine, postprocess
25+
from utils.utils import preprocess, invert_affine, postprocess, boolean_string
2626

2727
ap = argparse.ArgumentParser()
2828
ap.add_argument('-p', '--project', type=str, default='coco', help='project file that contains parameters')
2929
ap.add_argument('-c', '--compound_coef', type=int, default=0, help='coefficients of efficientdet')
3030
ap.add_argument('-w', '--weights', type=str, default=None, help='/path/to/weights')
3131
ap.add_argument('--nms_threshold', type=float, default=0.5, help='nms threshold, don\'t change it if not for testing purposes')
32-
ap.add_argument('--cuda', type=bool, default=True)
32+
ap.add_argument('--cuda', type=boolean_string, default=True)
3333
ap.add_argument('--device', type=int, default=0)
34-
ap.add_argument('--float16', type=bool, default=False)
35-
ap.add_argument('--override', type=bool, default=True, help='override previous bbox results file if exists')
34+
ap.add_argument('--float16', type=boolean_string, default=False)
35+
ap.add_argument('--override', type=boolean_string, default=True, help='override previous bbox results file if exists')
3636
args = ap.parse_args()
3737

3838
compound_coef = args.compound_coef
@@ -49,7 +49,7 @@
4949
params = yaml.safe_load(open(f'projects/{project_name}.yml'))
5050
obj_list = params['obj_list']
5151

52-
input_sizes = [512, 640, 768, 896, 1024, 1280, 1280, 1536]
52+
input_sizes = [512, 640, 768, 896, 1024, 1280, 1280, 1536, 1536]
5353

5454

5555
def evaluate_coco(img_path, set_name, image_ids, coco, model, threshold=0.05):

train.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,25 @@
22
# adapted from https://github.com/signatrix/efficientdet/blob/master/train.py
33
# modified by Zylo117
44

5+
import argparse
56
import datetime
67
import os
7-
import argparse
88
import traceback
99

10+
import numpy as np
1011
import torch
1112
import yaml
13+
from tensorboardX import SummaryWriter
1214
from torch import nn
1315
from torch.utils.data import DataLoader
1416
from torchvision import transforms
15-
from efficientdet.dataset import CocoDataset, Resizer, Normalizer, Augmenter, collater
16-
from backbone import EfficientDetBackbone
17-
from tensorboardX import SummaryWriter
18-
import numpy as np
1917
from tqdm.autonotebook import tqdm
2018

19+
from backbone import EfficientDetBackbone
20+
from efficientdet.dataset import CocoDataset, Resizer, Normalizer, Augmenter, collater
2121
from efficientdet.loss import FocalLoss
2222
from utils.sync_batchnorm import patch_replication_callback
23-
from utils.utils import replace_w_sync_bn, CustomDataParallel, get_last_weights, init_weights
23+
from utils.utils import replace_w_sync_bn, CustomDataParallel, get_last_weights, init_weights, boolean_string
2424

2525

2626
class Params:
@@ -56,19 +56,14 @@ def get_args():
5656
parser.add_argument('-w', '--load_weights', type=str, default=None,
5757
help='whether to load weights from a checkpoint, set None to initialize, set \'last\' to load last checkpoint')
5858
parser.add_argument('--saved_path', type=str, default='logs/')
59-
parser.add_argument('--debug', type=boolean_string, default=False, help='whether visualize the predicted boxes of training, '
60-
'the output images will be in test/')
59+
parser.add_argument('--debug', type=boolean_string, default=False,
60+
help='whether visualize the predicted boxes of training, '
61+
'the output images will be in test/')
6162

6263
args = parser.parse_args()
6364
return args
6465

6566

66-
def boolean_string(s):
67-
if s not in {'False', 'True'}:
68-
raise ValueError('Not a valid boolean string')
69-
return s == 'True'
70-
71-
7267
class ModelWithLoss(nn.Module):
7368
def __init__(self, model, debug=False):
7469
super().__init__()
@@ -308,7 +303,7 @@ def freeze_backbone(m):
308303
save_checkpoint(model, f'efficientdet-d{opt.compound_coef}_{epoch}_{step}.pth')
309304

310305
model.train()
311-
306+
312307
# Early stopping
313308
if epoch - best_epoch > opt.es_patience > 0:
314309
print('[Info] Stop training at epoch {}. The lowest loss achieved is {}'.format(epoch, best_loss))

utils/utils.py

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
# Author: Zylo117
22

3+
import math
34
import os
5+
import uuid
6+
from glob import glob
7+
from typing import Union
48

59
import cv2
610
import numpy as np
711
import torch
8-
from glob import glob
12+
import webcolors
913
from torch import nn
10-
from torchvision.ops import nms
14+
from torch.nn.init import _calculate_fan_in_and_fan_out, _no_grad_normal_
1115
from torchvision.ops.boxes import batched_nms
12-
from typing import Union
13-
import uuid
1416

1517
from utils.sync_batchnorm import SynchronizedBatchNorm2d
1618

17-
from torch.nn.init import _calculate_fan_in_and_fan_out, _no_grad_normal_
18-
import math
19-
import webcolors
2019

2120
def invert_affine(metas: Union[float, list, tuple], preds):
2221
for i in range(len(preds)):
@@ -245,7 +244,7 @@ def variance_scaling_(tensor, gain=1.):
245244

246245

247246
STANDARD_COLORS = [
248-
'LawnGreen', 'Chartreuse', 'Aqua','Beige', 'Azure','BlanchedAlmond','Bisque',
247+
'LawnGreen', 'Chartreuse', 'Aqua', 'Beige', 'Azure', 'BlanchedAlmond', 'Bisque',
249248
'Aquamarine', 'BlueViolet', 'BurlyWood', 'CadetBlue', 'AntiqueWhite',
250249
'Chocolate', 'Coral', 'CornflowerBlue', 'Cornsilk', 'Crimson', 'Cyan',
251250
'DarkCyan', 'DarkGoldenRod', 'DarkGrey', 'DarkKhaki', 'DarkOrange',
@@ -272,14 +271,14 @@ def variance_scaling_(tensor, gain=1.):
272271

273272

274273
def from_colorname_to_bgr(color):
275-
rgb_color=webcolors.name_to_rgb(color)
276-
result=(rgb_color.blue,rgb_color.green,rgb_color.red)
274+
rgb_color = webcolors.name_to_rgb(color)
275+
result = (rgb_color.blue, rgb_color.green, rgb_color.red)
277276
return result
278277

279278

280279
def standard_to_bgr(list_color_name):
281-
standard= []
282-
for i in range(len(list_color_name)-36): #-36 used to match the len(obj_list)
280+
standard = []
281+
for i in range(len(list_color_name) - 36): # -36 used to match the len(obj_list)
283282
standard.append(from_colorname_to_bgr(list_color_name[i]))
284283
return standard
285284

@@ -296,11 +295,18 @@ def plot_one_box(img, coord, label=None, score=None, color=None, line_thickness=
296295
cv2.rectangle(img, c1, c2, color, thickness=tl)
297296
if label:
298297
tf = max(tl - 2, 1) # font thickness
299-
s_size = cv2.getTextSize(str('{:.0%}'.format(score)),0, fontScale=float(tl) / 3, thickness=tf)[0]
298+
s_size = cv2.getTextSize(str('{:.0%}'.format(score)), 0, fontScale=float(tl) / 3, thickness=tf)[0]
300299
t_size = cv2.getTextSize(label, 0, fontScale=float(tl) / 3, thickness=tf)[0]
301-
c2 = c1[0] + t_size[0]+s_size[0]+15, c1[1] - t_size[1] -3
302-
cv2.rectangle(img, c1, c2 , color, -1) # filled
303-
cv2.putText(img, '{}: {:.0%}'.format(label, score), (c1[0],c1[1] - 2), 0, float(tl) / 3, [0, 0, 0], thickness=tf, lineType=cv2.FONT_HERSHEY_SIMPLEX)
300+
c2 = c1[0] + t_size[0] + s_size[0] + 15, c1[1] - t_size[1] - 3
301+
cv2.rectangle(img, c1, c2, color, -1) # filled
302+
cv2.putText(img, '{}: {:.0%}'.format(label, score), (c1[0], c1[1] - 2), 0, float(tl) / 3, [0, 0, 0],
303+
thickness=tf, lineType=cv2.FONT_HERSHEY_SIMPLEX)
304+
304305

305-
306306
color_list = standard_to_bgr(STANDARD_COLORS)
307+
308+
309+
def boolean_string(s):
310+
if s not in {'False', 'True'}:
311+
raise ValueError('Not a valid boolean string')
312+
return s == 'True'

0 commit comments

Comments
 (0)