Skip to content

Commit dc6b10e

Browse files
committed
Update python script
For works python3
1 parent 8a2f838 commit dc6b10e

File tree

16 files changed

+87
-81
lines changed

16 files changed

+87
-81
lines changed

cfgs/config.py

Lines changed: 2 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 *
3+
from .exps.darknet19_exp1 import *
44

55

66
def mkdir(path, max_depth=3):

darknet.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def _process_batch(data):
105105
ious_reshaped = np.reshape(ious, [hw, num_anchors, len(cell_inds)])
106106
for i, cell_ind in enumerate(cell_inds):
107107
if cell_ind >= hw or cell_ind < 0:
108-
print cell_ind
108+
print(cell_ind)
109109
continue
110110
a = anchor_inds[i]
111111

@@ -247,7 +247,7 @@ def load_from_npz(self, fname, num_conv=None):
247247
'bn.running_mean': 'moving_mean', 'bn.running_var': 'moving_variance'}
248248
params = np.load(fname)
249249
own_dict = self.state_dict()
250-
keys = own_dict.keys()
250+
keys = list(own_dict.keys())
251251

252252
for i, start in enumerate(range(0, len(keys), 5)):
253253
if num_conv is not None and i>= num_conv:
@@ -257,7 +257,7 @@ def load_from_npz(self, fname, num_conv=None):
257257
list_key = key.split('.')
258258
ptype = dest_src['{}.{}'.format(list_key[-2], list_key[-1])]
259259
src_key = '{}-convolutional/{}:0'.format(i, ptype)
260-
print(src_key, own_dict[key].size(), params[src_key].shape)
260+
print((src_key, own_dict[key].size(), params[src_key].shape))
261261
param = torch.from_numpy(params[src_key])
262262
if ptype == 'kernel':
263263
param = param.permute(3, 2, 0, 1)

datasets/pascal_voc.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import cPickle
1+
import pickle
22
import os
33
import uuid
44
import cv2
@@ -9,8 +9,8 @@
99

1010
# from functools import partial
1111

12-
from imdb import ImageDataset
13-
from voc_eval import voc_eval
12+
from .imdb import ImageDataset
13+
from .voc_eval import voc_eval
1414
# from utils.yolo import preprocess_train
1515

1616

@@ -30,7 +30,7 @@ def __init__(self, imdb_name, datadir, batch_size, im_processor, processes=3, sh
3030
'cow', 'diningtable', 'dog', 'horse',
3131
'motorbike', 'person', 'pottedplant',
3232
'sheep', 'sofa', 'train', 'tvmonitor')
33-
self._class_to_ind = dict(zip(self.classes, range(self.num_classes)))
33+
self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes)))))
3434
self._image_ext = '.jpg'
3535

3636
self._salt = str(uuid.uuid4())
@@ -102,15 +102,15 @@ def _load_pascal_annotations(self):
102102
cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl')
103103
if os.path.exists(cache_file):
104104
with open(cache_file, 'rb') as fid:
105-
roidb = cPickle.load(fid)
106-
print '{} gt roidb loaded from {}'.format(self.name, cache_file)
105+
roidb = pickle.load(fid)
106+
print('{} gt roidb loaded from {}'.format(self.name, cache_file))
107107
return roidb
108108

109109
gt_roidb = [self._annotation_from_index(index)
110110
for index in self.image_indexes]
111111
with open(cache_file, 'wb') as fid:
112-
cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL)
113-
print 'wrote gt roidb to {}'.format(cache_file)
112+
pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL)
113+
print('wrote gt roidb to {}'.format(cache_file))
114114

115115
return gt_roidb
116116

@@ -180,15 +180,15 @@ def _write_voc_results_file(self, all_boxes):
180180
for cls_ind, cls in enumerate(self.classes):
181181
if cls == '__background__':
182182
continue
183-
print 'Writing {} VOC results file'.format(cls)
183+
print('Writing {} VOC results file'.format(cls))
184184
filename = self._get_voc_results_file_template().format(cls)
185185
with open(filename, 'wt') as f:
186186
for im_ind, index in enumerate(self.image_indexes):
187187
dets = all_boxes[cls_ind][im_ind]
188188
if dets == []:
189189
continue
190190
# the VOCdevkit expects 1-based indices
191-
for k in xrange(dets.shape[0]):
191+
for k in range(dets.shape[0]):
192192
f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.
193193
format(index, dets[k, -1],
194194
dets[k, 0] + 1, dets[k, 1] + 1,
@@ -210,7 +210,7 @@ def _do_python_eval(self, output_dir='output'):
210210
aps = []
211211
# The PASCAL VOC metric changed in 2010
212212
use_07_metric = True if int(self._year) < 2010 else False
213-
print 'VOC07 metric? ' + ('Yes' if use_07_metric else 'No')
213+
print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))
214214
if output_dir is not None and not os.path.isdir(output_dir):
215215
os.mkdir(output_dir)
216216
for i, cls in enumerate(self._classes):
@@ -221,16 +221,16 @@ def _do_python_eval(self, output_dir='output'):
221221
filename, annopath, imagesetfile, cls, cachedir, ovthresh=0.5,
222222
use_07_metric=use_07_metric)
223223
aps += [ap]
224-
print('AP for {} = {:.4f}'.format(cls, ap))
224+
print(('AP for {} = {:.4f}'.format(cls, ap)))
225225
if output_dir is not None:
226226
with open(os.path.join(output_dir, cls + '_pr.pkl'), 'w') as f:
227-
cPickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)
228-
print('Mean AP = {:.4f}'.format(np.mean(aps)))
227+
pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)
228+
print(('Mean AP = {:.4f}'.format(np.mean(aps))))
229229
print('~~~~~~~~')
230230
print('Results:')
231231
for ap in aps:
232-
print('{:.3f}'.format(ap))
233-
print('{:.3f}'.format(np.mean(aps)))
232+
print(('{:.3f}'.format(ap)))
233+
print(('{:.3f}'.format(np.mean(aps))))
234234
print('~~~~~~~~')
235235
print('')
236236
print('--------------------------------------------------------------')

datasets/voc_eval.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import xml.etree.ElementTree as ET
88
import os
9-
import cPickle
9+
import pickle
1010
import numpy as np
1111
import pdb
1212

@@ -111,16 +111,16 @@ def voc_eval(detpath,
111111
for i, imagename in enumerate(imagenames):
112112
recs[imagename] = parse_rec(annopath.format(imagename))
113113
if i % 100 == 0:
114-
print 'Reading annotation for {:d}/{:d}'.format(
115-
i + 1, len(imagenames))
114+
print('Reading annotation for {:d}/{:d}'.format(
115+
i + 1, len(imagenames)))
116116
# save
117-
print 'Saving cached annotations to {:s}'.format(cachefile)
117+
print('Saving cached annotations to {:s}'.format(cachefile))
118118
with open(cachefile, 'w') as f:
119-
cPickle.dump(recs, f)
119+
pickle.dump(recs, f)
120120
else:
121121
# load
122122
with open(cachefile, 'r') as f:
123-
recs = cPickle.load(f)
123+
recs = pickle.load(f)
124124

125125
# extract gt objects for this class
126126
class_recs = {}

demo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ def preprocess(fname):
6969

7070
if i % 1 == 0:
7171
format_str = 'frame: %d, (detection: %.1f Hz, %.1f ms) (total: %.1f Hz, %.1f ms)'
72-
print(format_str % (
73-
i, 1. / det_time, det_time * 1000, 1. / total_time, total_time * 1000))
72+
print((format_str % (
73+
i, 1. / det_time, det_time * 1000, 1. / total_time, total_time * 1000)))
7474

7575
t_total.clear()
7676
t_det.clear()

layers/reorg/_ext/reorg_layer/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66
def _import_symbols(locals):
77
for symbol in dir(_lib):
88
fn = getattr(_lib, symbol)
9-
locals[symbol] = _wrap_function(fn, _ffi)
9+
if callable(fn):
10+
locals[symbol] = _wrap_function(fn, _ffi)
11+
else:
12+
locals[symbol] = fn
1013
__all__.append(symbol)
1114

1215
_import_symbols(locals())

layers/roi_pooling/_ext/roi_pooling/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66
def _import_symbols(locals):
77
for symbol in dir(_lib):
88
fn = getattr(_lib, symbol)
9-
locals[symbol] = _wrap_function(fn, _ffi)
9+
if callable(fn):
10+
locals[symbol] = _wrap_function(fn, _ffi)
11+
else:
12+
locals[symbol] = fn
1013
__all__.append(symbol)
1114

1215
_import_symbols(locals())

layers/roi_pooling/roi_pool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import torch
22
from torch.autograd import Function
3-
from _ext import roi_pooling
3+
from ._ext import roi_pooling
44

55

66
class RoIPoolFunction(Function):

test.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import cv2
33
import torch
44
import numpy as np
5-
import cPickle
5+
import pickle
66

77
from darknet import Darknet19
88
import utils.yolo as yolo_utils
@@ -38,8 +38,8 @@ def test_net(net, imdb, max_per_image=300, thresh=0.5, vis=False):
3838
# all detections are collected into:
3939
# all_boxes[cls][image] = N x 5 array of detections in
4040
# (x1, y1, x2, y2, score)
41-
all_boxes = [[[] for _ in xrange(num_images)]
42-
for _ in xrange(imdb.num_classes)]
41+
all_boxes = [[[] for _ in range(num_images)]
42+
for _ in range(imdb.num_classes)]
4343

4444
# timers
4545
_t = {'im_detect': Timer(), 'misc': Timer()}
@@ -79,14 +79,14 @@ def test_net(net, imdb, max_per_image=300, thresh=0.5, vis=False):
7979
image_scores = np.hstack([all_boxes[j][i][:, -1] for j in range(imdb.num_classes)])
8080
if len(image_scores) > max_per_image:
8181
image_thresh = np.sort(image_scores)[-max_per_image]
82-
for j in xrange(1, imdb.num_classes):
82+
for j in range(1, imdb.num_classes):
8383
keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0]
8484
all_boxes[j][i] = all_boxes[j][i][keep, :]
8585
nms_time = _t['misc'].toc()
8686

8787
if i % 20 == 0:
88-
print 'im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \
89-
.format(i + 1, num_images, detect_time, nms_time)
88+
print('im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \
89+
.format(i + 1, num_images, detect_time, nms_time))
9090
_t['im_detect'].clear()
9191
_t['misc'].clear()
9292

@@ -98,9 +98,9 @@ def test_net(net, imdb, max_per_image=300, thresh=0.5, vis=False):
9898
cv2.waitKey(0)
9999

100100
with open(det_file, 'wb') as f:
101-
cPickle.dump(all_boxes, f, cPickle.HIGHEST_PROTOCOL)
101+
pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)
102102

103-
print 'Evaluating detections'
103+
print('Evaluating detections')
104104
imdb.evaluate_detections(all_boxes, output_dir)
105105

106106

train.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,9 @@
9494
bbox_loss /= cnt
9595
iou_loss /= cnt
9696
cls_loss /= cnt
97-
print('epoch %d[%d/%d], loss: %.3f, bbox_loss: %.3f, iou_loss: %.3f, cls_loss: %.3f (%.2f s/batch, rest:%s)' % (
97+
print(('epoch %d[%d/%d], loss: %.3f, bbox_loss: %.3f, iou_loss: %.3f, cls_loss: %.3f (%.2f s/batch, rest:%s)' % (
9898
imdb.epoch, step_cnt, batch_per_epoch, train_loss, bbox_loss, iou_loss, cls_loss, duration,
99-
str(datetime.timedelta(seconds=int((batch_per_epoch - step_cnt) * duration)))))
99+
str(datetime.timedelta(seconds=int((batch_per_epoch - step_cnt) * duration))))))
100100

101101
if use_tensorboard and step % cfg.log_interval == 0:
102102
exp.add_scalar_value('loss_train', train_loss, step=step)
@@ -117,7 +117,7 @@
117117

118118
save_name = os.path.join(cfg.train_output_dir, '{}_{}.h5'.format(cfg.exp_name, imdb.epoch))
119119
net_utils.save_net(save_name, net)
120-
print('save model: {}'.format(save_name))
120+
print(('save model: {}'.format(save_name)))
121121
step_cnt = 0
122122

123123
imdb.close()

0 commit comments

Comments
 (0)