Skip to content

Commit 1b320fa

Browse files
committed
# Update python script
For fix flake8
1 parent 216ad59 commit 1b320fa

File tree

21 files changed

+460
-292
lines changed

21 files changed

+460
-292
lines changed

cfgs/config.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import os
2-
from .config_voc import *
3-
from .exps.darknet19_exp1 import *
2+
from .config_voc import * # noqa
3+
from .exps.darknet19_exp1 import * # noqa
44

55

66
def mkdir(path, max_depth=3):
@@ -50,6 +50,7 @@ def _to_color(indx, base):
5050
g = 2 - (indx % base2) % base
5151
return b * 127, r * 127, g * 127
5252

53+
5354
base = int(np.ceil(pow(num_classes, 1. / 3)))
5455
colors = [_to_color(x, base) for x in range(num_classes)]
5556

cfgs/config_voc.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
'sheep', 'sofa', 'train', 'tvmonitor')
1313
num_classes = len(label_names)
1414

15-
anchors = np.asarray([(1.08, 1.19), (3.42, 4.41), (6.63, 11.38), (9.42, 5.11), (16.62, 10.52)], dtype=np.float)
15+
anchors = np.asarray([(1.08, 1.19), (3.42, 4.41),
16+
(6.63, 11.38), (9.42, 5.11), (16.62, 10.52)],
17+
dtype=np.float)
1618
num_anchors = len(anchors)
17-

darknet.py

Lines changed: 42 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
from functools import partial
1212

1313
from multiprocessing import Pool
14-
import multiprocessing
1514

1615

1716
def _make_layers(in_channels, net_cfg):
@@ -67,7 +66,8 @@ def _process_batch(data, size_index):
6766
np.ascontiguousarray(bbox_pred_np, dtype=np.float),
6867
anchors,
6968
H, W)
70-
bbox_np = bbox_np[0] # bbox_np = (hw, num_anchors, (x1, y1, x2, y2)) range: 0 ~ 1
69+
# bbox_np = (hw, num_anchors, (x1, y1, x2, y2)) range: 0 ~ 1
70+
bbox_np = bbox_np[0]
7171
bbox_np[:, :, 0::2] *= float(inp_size[0]) # rescale x
7272
bbox_np[:, :, 1::2] *= float(inp_size[1]) # rescale y
7373

@@ -95,8 +95,10 @@ def _process_batch(data, size_index):
9595
target_boxes = np.empty(gt_boxes_b.shape, dtype=np.float)
9696
target_boxes[:, 0] = cx - np.floor(cx) # cx
9797
target_boxes[:, 1] = cy - np.floor(cy) # cy
98-
target_boxes[:, 2] = (gt_boxes_b[:, 2] - gt_boxes_b[:, 0]) / inp_size[0] * out_size[0] # tw
99-
target_boxes[:, 3] = (gt_boxes_b[:, 3] - gt_boxes_b[:, 1]) / inp_size[1] * out_size[1] # th
98+
target_boxes[:, 2] = \
99+
(gt_boxes_b[:, 2] - gt_boxes_b[:, 0]) / inp_size[0] * out_size[0] # tw
100+
target_boxes[:, 3] = \
101+
(gt_boxes_b[:, 3] - gt_boxes_b[:, 1]) / inp_size[1] * out_size[1] # th
100102

101103
# for each gt boxes, match the best anchor
102104
gt_boxes_resize = np.copy(gt_boxes_b)
@@ -116,8 +118,9 @@ def _process_batch(data, size_index):
116118
continue
117119
a = anchor_inds[i]
118120

119-
iou_pred_cell_anchor = iou_pred_np[cell_ind, a, :] # 0 ~ 1, should be close to 1
120-
_iou_mask[cell_ind, a, :] = cfg.object_scale * (1 - iou_pred_cell_anchor)
121+
# 0 ~ 1, should be close to 1
122+
iou_pred_cell_anchor = iou_pred_np[cell_ind, a, :]
123+
_iou_mask[cell_ind, a, :] = cfg.object_scale * (1 - iou_pred_cell_anchor) # noqa
121124
# _ious[cell_ind, a, :] = anchor_ious[a, i]
122125
_ious[cell_ind, a, :] = ious_reshaped[cell_ind, a, i]
123126

@@ -169,7 +172,7 @@ def __init__(self):
169172
# linear
170173
out_channels = cfg.num_anchors * (cfg.num_classes + 5)
171174
self.conv5 = net_utils.Conv2d(c4, out_channels, 1, 1, relu=False)
172-
self.global_average_pool = nn.AvgPool2d((1,1))
175+
self.global_average_pool = nn.AvgPool2d((1, 1))
173176

174177
# train
175178
self.bbox_loss = None
@@ -181,7 +184,8 @@ def __init__(self):
181184
def loss(self):
182185
return self.bbox_loss + self.iou_loss + self.cls_loss
183186

184-
def forward(self, im_data, gt_boxes=None, gt_classes=None, dontcare=None, size_index=0):
187+
def forward(self, im_data, gt_boxes=None, gt_classes=None, dontcare=None,
188+
size_index=0):
185189
conv1s = self.conv1s(im_data)
186190
conv2 = self.conv2(conv1s)
187191
conv3 = self.conv3(conv2)
@@ -192,10 +196,13 @@ def forward(self, im_data, gt_boxes=None, gt_classes=None, dontcare=None, size_i
192196
global_average_pool = self.global_average_pool(conv5)
193197

194198
# for detection
195-
# bsize, c, h, w -> bsize, h, w, c -> bsize, h x w, num_anchors, 5+num_classes
199+
# bsize, c, h, w -> bsize, h, w, c ->
200+
# bsize, h x w, num_anchors, 5+num_classes
196201
bsize, _, h, w = global_average_pool.size()
197202
# assert bsize == 1, 'detection only support one image per batch'
198-
global_average_pool_reshaped = global_average_pool.permute(0, 2, 3, 1).contiguous().view(bsize, -1, cfg.num_anchors, cfg.num_classes + 5)
203+
global_average_pool_reshaped = \
204+
global_average_pool.permute(0, 2, 3, 1).contiguous().view(bsize,
205+
-1, cfg.num_anchors, cfg.num_classes + 5) # noqa
199206

200207
# tx, ty, tw, th, to -> sig(tx), sig(ty), exp(tw), exp(th), sig(to)
201208
xy_pred = F.sigmoid(global_average_pool_reshaped[:, :, :, 0:2])
@@ -204,44 +211,55 @@ def forward(self, im_data, gt_boxes=None, gt_classes=None, dontcare=None, size_i
204211
iou_pred = F.sigmoid(global_average_pool_reshaped[:, :, :, 4:5])
205212

206213
score_pred = global_average_pool_reshaped[:, :, :, 5:].contiguous()
207-
prob_pred = F.softmax(score_pred.view(-1, score_pred.size()[-1])).view_as(score_pred)
214+
prob_pred = F.softmax(score_pred.view(-1, score_pred.size()[-1])).view_as(score_pred) # noqa
208215

209216
# for training
210217
if self.training:
211218
bbox_pred_np = bbox_pred.data.cpu().numpy()
212219
iou_pred_np = iou_pred.data.cpu().numpy()
213-
_boxes, _ious, _classes, _box_mask, _iou_mask, _class_mask = self._build_target(
214-
bbox_pred_np, gt_boxes, gt_classes, dontcare, iou_pred_np, size_index)
220+
_boxes, _ious, _classes, _box_mask, _iou_mask, _class_mask = \
221+
self._build_target(bbox_pred_np,
222+
gt_boxes,
223+
gt_classes,
224+
dontcare,
225+
iou_pred_np,
226+
size_index)
215227

216228
_boxes = net_utils.np_to_variable(_boxes)
217229
_ious = net_utils.np_to_variable(_ious)
218230
_classes = net_utils.np_to_variable(_classes)
219-
box_mask = net_utils.np_to_variable(_box_mask, dtype=torch.FloatTensor)
220-
iou_mask = net_utils.np_to_variable(_iou_mask, dtype=torch.FloatTensor)
221-
class_mask = net_utils.np_to_variable(_class_mask, dtype=torch.FloatTensor)
231+
box_mask = net_utils.np_to_variable(_box_mask,
232+
dtype=torch.FloatTensor)
233+
iou_mask = net_utils.np_to_variable(_iou_mask,
234+
dtype=torch.FloatTensor)
235+
class_mask = net_utils.np_to_variable(_class_mask,
236+
dtype=torch.FloatTensor)
222237

223238
num_boxes = sum((len(boxes) for boxes in gt_boxes))
224239

225240
# _boxes[:, :, :, 2:4] = torch.log(_boxes[:, :, :, 2:4])
226241
box_mask = box_mask.expand_as(_boxes)
227242

228-
self.bbox_loss = nn.MSELoss(size_average=False)(bbox_pred * box_mask, _boxes * box_mask) / num_boxes
229-
self.iou_loss = nn.MSELoss(size_average=False)(iou_pred * iou_mask, _ious * iou_mask) / num_boxes
243+
self.bbox_loss = nn.MSELoss(size_average=False)(bbox_pred * box_mask, _boxes * box_mask) / num_boxes # noqa
244+
self.iou_loss = nn.MSELoss(size_average=False)(iou_pred * iou_mask, _ious * iou_mask) / num_boxes # noqa
230245

231246
class_mask = class_mask.expand_as(prob_pred)
232-
self.cls_loss = nn.MSELoss(size_average=False)(prob_pred * class_mask, _classes * class_mask) / num_boxes
247+
self.cls_loss = nn.MSELoss(size_average=False)(prob_pred * class_mask, _classes * class_mask) / num_boxes # noqa
233248

234249
return bbox_pred, iou_pred, prob_pred
235250

236-
def _build_target(self, bbox_pred_np, gt_boxes, gt_classes, dontcare, iou_pred_np, size_index):
251+
def _build_target(self, bbox_pred_np, gt_boxes, gt_classes, dontcare,
252+
iou_pred_np, size_index):
237253
"""
238-
:param bbox_pred: shape: (bsize, h x w, num_anchors, 4) : (sig(tx), sig(ty), exp(tw), exp(th))
254+
:param bbox_pred: shape: (bsize, h x w, num_anchors, 4) :
255+
(sig(tx), sig(ty), exp(tw), exp(th))
239256
"""
240257

241258
bsize = bbox_pred_np.shape[0]
242259

243260
targets = self.pool.map(partial(_process_batch, size_index=size_index),
244-
((bbox_pred_np[b], gt_boxes[b], gt_classes[b], dontcare[b], iou_pred_np[b])
261+
((bbox_pred_np[b], gt_boxes[b],
262+
gt_classes[b], dontcare[b], iou_pred_np[b])
245263
for b in range(bsize)))
246264

247265
_boxes = np.stack(tuple((row[0] for row in targets)))
@@ -256,7 +274,8 @@ def _build_target(self, bbox_pred_np, gt_boxes, gt_classes, dontcare, iou_pred_n
256274
def load_from_npz(self, fname, num_conv=None):
257275
dest_src = {'conv.weight': 'kernel', 'conv.bias': 'biases',
258276
'bn.weight': 'gamma', 'bn.bias': 'biases',
259-
'bn.running_mean': 'moving_mean', 'bn.running_var': 'moving_variance'}
277+
'bn.running_mean': 'moving_mean',
278+
'bn.running_var': 'moving_variance'}
260279
params = np.load(fname)
261280
own_dict = self.state_dict()
262281
keys = list(own_dict.keys())

datasets/imdb.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import os
2-
import PIL
32
import numpy as np
43
from multiprocessing import Pool
54
from functools import partial
@@ -23,7 +22,8 @@ def image_resize(im, size_index):
2322

2423

2524
class ImageDataset(object):
26-
def __init__(self, name, datadir, batch_size, im_processor, processes=3, shuffle=True, dst_size=None):
25+
def __init__(self, name, datadir, batch_size, im_processor,
26+
processes=3, shuffle=True, dst_size=None):
2727
self._name = name
2828
self._data_dir = datadir
2929
self._batch_size = batch_size
@@ -48,7 +48,8 @@ def __init__(self, name, datadir, batch_size, im_processor, processes=3, shuffle
4848
self._im_processor = im_processor
4949

5050
def next_batch(self, size_index):
51-
batch = {'images': [], 'gt_boxes': [], 'gt_classes': [], 'dontcare': [], 'origin_im': []}
51+
batch = {'images': [], 'gt_boxes': [], 'gt_classes': [],
52+
'dontcare': [], 'origin_im': []}
5253
i = 0
5354
while i < self.batch_size:
5455
try:
@@ -64,8 +65,11 @@ def next_batch(self, size_index):
6465
indexes = np.arange(len(self.image_names), dtype=np.int)
6566
if self._shuffle:
6667
np.random.shuffle(indexes)
67-
self.gen = self.pool.imap(partial(self._im_processor, size_index=size_index),
68-
([self.image_names[i], self.get_annotation(i), self.dst_size] for i in indexes),
68+
self.gen = self.pool.imap(partial(self._im_processor,
69+
size_index=size_index),
70+
([self.image_names[i],
71+
self.get_annotation(i),
72+
self.dst_size] for i in indexes),
6973
chunksize=self.batch_size)
7074
self._epoch += 1
7175
print(('epoch {} start...'.format(self._epoch)))
@@ -141,5 +145,3 @@ def batch_size(self):
141145
@property
142146
def batch_per_epoch(self):
143147
return self.num_images // self.batch_size
144-
145-

datasets/pascal_voc.py

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import pickle
22
import os
33
import uuid
4-
import cv2
54
import xml.etree.ElementTree as ET
65

76
import numpy as np
@@ -15,22 +14,30 @@
1514

1615

1716
class VOCDataset(ImageDataset):
18-
def __init__(self, imdb_name, datadir, batch_size, im_processor, processes=3, shuffle=True, dst_size=None):
19-
super(VOCDataset, self).__init__(imdb_name, datadir, batch_size, im_processor, processes, shuffle, dst_size)
17+
def __init__(self, imdb_name, datadir, batch_size, im_processor,
18+
processes=3, shuffle=True, dst_size=None):
19+
super(VOCDataset, self).__init__(imdb_name, datadir, batch_size,
20+
im_processor, processes,
21+
shuffle, dst_size)
2022
meta = imdb_name.split('_')
2123
self._year = meta[1]
2224
self._image_set = meta[2]
23-
self._devkit_path = os.path.join(datadir, 'VOCdevkit{}'.format(self._year))
24-
self._data_path = os.path.join(self._devkit_path, 'VOC{}'.format(self._year))
25-
assert os.path.exists(self._devkit_path), 'VOCdevkit path does not exist: {}'.format(self._devkit_path)
26-
assert os.path.exists(self._data_path), 'Path does not exist: {}'.format(self._data_path)
25+
self._devkit_path = os.path.join(datadir,
26+
'VOCdevkit{}'.format(self._year))
27+
self._data_path = os.path.join(self._devkit_path,
28+
'VOC{}'.format(self._year))
29+
assert os.path.exists(self._devkit_path), \
30+
'VOCdevkit path does not exist: {}'.format(self._devkit_path)
31+
assert os.path.exists(self._data_path), \
32+
'Path does not exist: {}'.format(self._data_path)
2733

2834
self._classes = ('aeroplane', 'bicycle', 'bird', 'boat',
2935
'bottle', 'bus', 'car', 'cat', 'chair',
3036
'cow', 'diningtable', 'dog', 'horse',
3137
'motorbike', 'person', 'pottedplant',
3238
'sheep', 'sofa', 'train', 'tvmonitor')
33-
self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes)))))
39+
self._class_to_ind = dict(list(zip(self.classes,
40+
list(range(self.num_classes)))))
3441
self._image_ext = '.jpg'
3542

3643
self._salt = str(uuid.uuid4())
@@ -41,13 +48,15 @@ def __init__(self, imdb_name, datadir, batch_size, im_processor, processes=3, sh
4148
'use_salt': True}
4249

4350
self.load_dataset()
44-
# self.im_processor = partial(process_im, image_names=self._image_names, annotations=self._annotations)
51+
# self.im_processor = partial(process_im,
52+
# image_names=self._image_names, annotations=self._annotations)
4553
# self.im_processor = preprocess_train
4654

4755
def load_dataset(self):
4856
# set self._image_index and self._annotations
4957
self._image_indexes = self._load_image_set_index()
50-
self._image_names = [self.image_path_from_index(index) for index in self.image_indexes]
58+
self._image_names = [self.image_path_from_index(index)
59+
for index in self.image_indexes]
5160
self._annotations = self._load_pascal_annotations()
5261

5362
def evaluate_detections(self, all_boxes, output_dir=None):
@@ -97,7 +106,8 @@ def _load_pascal_annotations(self):
97106
"""
98107
Return the database of ground-truth regions of interest.
99108
100-
This function loads/saves from/to a cache file to speed up future calls.
109+
This function loads/saves from/to a cache file to speed up
110+
future calls.
101111
"""
102112
cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl')
103113
if os.path.exists(cache_file):
@@ -149,7 +159,7 @@ def _annotation_from_index(self, index):
149159
y2 = float(bbox.find('ymax').text) - 1
150160

151161
diffc = obj.find('difficult')
152-
difficult = 0 if diffc == None else int(diffc.text)
162+
difficult = 0 if diffc is None else int(diffc.text)
153163
ishards[ix] = difficult
154164

155165
cls = self._class_to_ind[obj.find('name').text.lower().strip()]
@@ -169,8 +179,10 @@ def _annotation_from_index(self, index):
169179

170180
def _get_voc_results_file_template(self):
171181
# VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt
172-
filename = self._get_comp_id() + '_det_' + self._image_set + '_{:s}.txt'
173-
filedir = os.path.join(self._devkit_path, 'results', 'VOC' + self._year, 'Main')
182+
filename = self._get_comp_id() + '_det_' + self._image_set + \
183+
'_{:s}.txt'
184+
filedir = os.path.join(self._devkit_path,
185+
'results', 'VOC' + self._year, 'Main')
174186
if not os.path.exists(filedir):
175187
os.makedirs(filedir)
176188
path = os.path.join(filedir, filename)

datasets/voc_eval.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import os
99
import pickle
1010
import numpy as np
11-
import pdb
1211

1312

1413
def parse_rec(filename):
@@ -64,6 +63,7 @@ def voc_ap(rec, prec, use_07_metric=False):
6463
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
6564
return ap
6665

66+
6767
def voc_eval(detpath,
6868
annopath,
6969
imagesetfile,
@@ -148,7 +148,6 @@ def voc_eval(detpath,
148148

149149
# sort by confidence
150150
sorted_ind = np.argsort(-confidence)
151-
sorted_scores = np.sort(-confidence)
152151
BB = BB[sorted_ind, :]
153152
image_ids = [image_ids[x] for x in sorted_ind]
154153

@@ -201,8 +200,8 @@ def voc_eval(detpath,
201200
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
202201
ap = voc_ap(rec, prec, use_07_metric)
203202
else:
204-
rec = -1
205-
prec = -1
206-
ap = -1
203+
rec = -1
204+
prec = -1
205+
ap = -1
207206

208207
return rec, prec, ap

0 commit comments

Comments
 (0)