本文整理汇总了Python中utils.timer.Timer类的典型用法代码示例。如果您正苦于以下问题:Python Timer类的具体用法?Python Timer怎么用?Python Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Timer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: demo
def demo(sess, net, im_file, result_dir, viz=False, oriented=False):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image
im = helper.read_rgb_img(im_file)
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes, resized_im_shape, im_scale = im_detect(sess, net, im)
timer.toc()
im = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)
img_name = im_file.split('/')[-1]
draw_rpn_boxes(im, img_name, boxes, scores[:, np.newaxis], im_scale, True, result_dir)
draw_rpn_boxes(im, img_name, boxes, scores[:, np.newaxis], im_scale, False, result_dir)
# Run TextDetector to merge small box
line_detector = TextDetector(oriented)
# line_detector 的输入必须是在 scale 之后的图片上!!,
# 如果还原了以后再进行行构建,原图可能太大,导致每个 anchor 的 width 很大,导致 MAX_HORIZONTAL_GAP 太小
# text_lines point order: left-top, right-top, left-bottom, right-bottom
text_lines = line_detector.detect(boxes, scores[:, np.newaxis], resized_im_shape)
print("Image %s, detect %d text lines in %.3fs" % (im_file, len(text_lines), timer.diff))
if len(text_lines) != 0:
text_lines = recover_scale(text_lines, im_scale)
save_result(im, img_name, text_lines, result_dir)
# Visualize detections
if viz:
vis_detections(im, CLASSES[1], text_lines)
示例2: train_with_hard_negatives
def train_with_hard_negatives(self):
_t = Timer()
roidb = self.imdb.roidb
num_images = len(roidb)
# num_images = 100
for i in xrange(num_images):
im = cv2.imread(self.imdb.image_path_at(i))
if roidb[i]['flipped']:
im = im[:, ::-1, :]
_t.tic()
scores, boxes = im_detect(self.net, im, roidb[i]['boxes'])
_t.toc()
feat = self.net.blobs[self.layer].data
for j in xrange(1, self.imdb.num_classes):
hard_inds = \
np.where((scores[:, j] > self.hard_thresh) &
(roidb[i]['gt_overlaps'][:, j].toarray().ravel() <
self.neg_iou_thresh))[0]
if len(hard_inds) > 0:
hard_feat = feat[hard_inds, :].copy()
new_w_b = \
self.trainers[j].append_neg_and_retrain(feat=hard_feat)
if new_w_b is not None:
self.update_net(j, new_w_b[0], new_w_b[1])
print(('train_with_hard_negatives: '
'{:d}/{:d} {:.3f}s').format(i + 1, len(roidb),
_t.average_time))
示例3: load_model_h5
def load_model_h5(weight_file):
darknet = DarkNet()
model = SimpleNet(darknet)
model.load_weights(weight_file)
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
timer = Timer()
timer.tic()
model.compile(optimizer=sgd, loss='categorical_crossentropy')
timer.toc()
print 'Total compile time is {:.3f}s'.format(timer.total_time)
for i in xrange(len(model.layers)):
print model.layers[i]
print model.layers[i].input_shape, model.layers[i].output_shape
weights = model.layers[i].get_weights()
if not weights is None and len(weights) > 0:
print weights[0].shape, weights[0].max(), weights[0].min()
# if len(weights) > 1:
# # print weights[0].shape, weights[0].max(), weights[0].min()
# # print "layer: %d" % (i)
# # w = weights[0].transpose()
# # w = weights[1]
# # print w.shape
# # cnt = 0
# # for val in w.flatten():
# # # print >> f, val
# # print 'weights[1]', cnt, ':', val
# # cnt += 1
# # raw_input()
# # print model.layers[4].get_weights()[0].shape, model.layers[4].get_weights()[1].shape
# # weights = model.layers[4].get_weights()[0]
# weights = weights[0]
# vis_square(weights.reshape((weights.shape[0]*weights.shape[1], weights.shape[2], weights.shape[3])))
return model
示例4: demo
def demo(net, im_file):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image as gray scale
gim = cv2.imread(im_file, flags= cv2.CV_LOAD_IMAGE_GRAYSCALE)
# convert to rgb repeated in each channel
im = cv2.cvtColor(gim, cv2.COLOR_GRAY2BGR)
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
# Visualize detections for each class
CONF_THRESH = 0.8
NMS_THRESH = 0.3
for cls_ind, cls in enumerate(CLASSES[1:]):
cls_ind += 1 # because we skipped background
cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
cls_scores = scores[:, cls_ind]
dets = np.hstack((cls_boxes,
cls_scores[:, np.newaxis])).astype(np.float32)
keep = nms(dets, NMS_THRESH)
dets = dets[keep, :]
vis_detections(im, cls, dets, thresh=CONF_THRESH)
示例5: Detect
def Detect(net, image_path):
"""Detect object classes in an image assuming the whole image is an object."""
# Load the image
im = cv2.imread(image_path)
h, w, c = im.shape
# TODO: Run selective search first
#
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im, np.array([[0, 0, w, h]]))
timer.toc()
scores = scores[0]
# get top 6 prediction
pred_classes = [CLASSES[idx] for idx in ((-scores).argsort()[:6]).tolist()]
conf = [ (-1) * prob for prob in np.sort(-scores)[:6].tolist()]
img_blob = {}
img_blob['image_path'] = image_path
img_blob['pred'] = {'text': pred_classes, 'conf': conf}
img_blob['rcnn_time'] = timer.total_time
return img_blob
示例6: demo
def demo(net, image_name):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image
im_file = os.path.join(cfg.ROOT_DIR, 'data', 'demo', image_name)
im = cv2.imread(im_file)
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
# Visualize detections for each class
CONF_THRESH = 0.8
NMS_THRESH = 0.3
for cls_ind, cls in enumerate(CLASSES[1:]):
cls_ind += 1 # because we skipped background\
cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
cls_scores = scores[:, cls_ind]
dets = np.hstack((cls_boxes,
cls_scores[:, np.newaxis])).astype(np.float32)
order = cls_scores.argsort()[::-1]
sorted_dets = dets[order, :]
keep = nms(dets, NMS_THRESH)
with open('/home/xyy/Desktop/doing/Object Detection/py-faster-rcnn/test_python.txt','w') as f:
dets = dets[keep, :]
for i in dets:
for j in i:
f.write(str(j)+ ' ')
f.write('\n')
vis_detections(im, cls, dets, thresh=CONF_THRESH)
示例7: _get_feature_scale
def _get_feature_scale(self, num_images=100):
TARGET_NORM = 20.0 # Magic value from traditional R-CNN
_t = Timer()
roidb = self.imdb.roidb
total_norm = 0.0
count = 0.0
inds = npr.choice(
range(self.imdb.num_images), size=num_images,
replace=False
)
for i_, i in enumerate(inds):
im = cv2.imread(self.imdb.image_path_at(i))
if roidb[i]['flipped']:
im = im[:, ::-1, :]
_t.tic()
scores, boxes = im_detect(self.net, im, roidb[i]['boxes'])
_t.toc()
feat = self.net.blobs[self.layer].data
total_norm += np.sqrt((feat ** 2).sum(axis=1)).sum()
count += feat.shape[0]
print('{}/{}: avg feature norm: {:.3f}'.format(
i_ + 1, num_images,
total_norm / count
)
)
return TARGET_NORM * 1.0 / (total_norm / count)
示例8: tattoo_detection
def tattoo_detection(net, image_name, args):
"""Detect object classes in an image using pre-computed object proposals."""
im_in = cv2.imread(image_name)
if im_in is None:
print('cannot open %s for read' % image_name )
exit(-1)
rows,cols = im_in.shape[:2]
print([rows,cols])
scale=1.0
if rows >= cols:
scale = float(args.longdim) / float(rows)
im = cv2.resize( im_in, (int(0.5 + float(cols)*scale), args.longdim) )
else:
scale = float(args.longdim) / float(cols)
im = cv2.resize( im_in, (args.longdim, int(0.5 + float(rows)*scale)) )
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im)
timer.toc()
seconds = '%.3f' % timer.total_time
print('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
max_scores = scores.max(axis=0)
print(max_scores)
print(boxes.shape)
# Visualize detections for each class
CONF_THRESH = args.threshold
NMS_THRESH = args.nms_thresh
tattoo_dets=[]
for cls_ind, cls in enumerate(CLASSES[1:]):
cls_ind += 1 # because we skipped background
cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
cls_scores = scores[:, cls_ind]
dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])).astype(np.float32)
keep = nms(dets, NMS_THRESH)
dets = dets[keep, :]
inds = np.where(dets[:, -1] >= CONF_THRESH)[0]
dets_filter = dets[inds]
vis_detections(im, cls, dets_filter, thresh=CONF_THRESH)
if cls == 'tattoo' and len(dets_filter)>0:
plt.savefig(os.path.join(args.output, os.path.splitext(os.path.basename(image_name))[0] + '_det.png'))
tattoo_dets = dets_filter
if args.inspect == 'v':
plt.show()
plt.clf()
return tattoo_dets, max_scores, seconds, scale
示例9: demo
def demo(sess, net, image_name):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image
im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name)
#im_file = os.path.join('/home/corgi/Lab/label/pos_frame/ACCV/training/000001/',image_name)
im = cv2.imread(im_file)
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(sess, net, im)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
# Visualize detections for each class
im = im[:, :, (2, 1, 0)]
fig, ax = plt.subplots(figsize=(12, 12))
ax.imshow(im, aspect='equal')
CONF_THRESH = 0.8
NMS_THRESH = 0.3
for cls_ind, cls in enumerate(CLASSES[1:]):
cls_ind += 1 # because we skipped background
cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
cls_scores = scores[:, cls_ind]
dets = np.hstack((cls_boxes,
cls_scores[:, np.newaxis])).astype(np.float32)
keep = nms(dets, NMS_THRESH)
dets = dets[keep, :]
vis_detections(im, cls, dets, ax, thresh=CONF_THRESH)
示例10: demoRest
def demoRest(net, image_name, classes, box_file, obj_proposals, im_file, im):
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im, obj_proposals)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
# Visualize detections for each class
CONF_THRESH = 0.8
NMS_THRESH = 0.3
for cls in classes:
cls_ind = CLASSES.index(cls)
cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
cls_scores = scores[:, cls_ind]
keep = np.where(cls_scores >= CONF_THRESH)[0]
cls_boxes = cls_boxes[keep, :]
cls_scores = cls_scores[keep]
dets = np.hstack((cls_boxes,
cls_scores[:, np.newaxis])).astype(np.float32)
keep = nms(dets, NMS_THRESH)
dets = dets[keep, :]
print 'All {} detections with p({} | box) >= {:.1f}'.format(cls, cls,
CONF_THRESH)
vis_detections(im, cls, dets, thresh=CONF_THRESH)
示例11: train_whole_model
def train_whole_model(self, tester=None):
'''
test the performance using all the features
may be memory consuming.
'''
self.comm.barrier()
mpi.rootprint('*'*46)
mpi.rootprint('*'*15+'whole featureset'+'*'*15)
mpi.rootprint('*'*46)
if tester is not None:
# normalize the test data with the stats of the training data
tester.normalize_data(self.mLocal, self.stdLocal)
timer = Timer()
timer.reset()
if self.maxGraftDim != self.nMetabins*self.nCodes:
mpi.rootprint('Please initialize with maxGraftDim=nMetabins*nCodes')
return
self.nSelFeats = 0
self.isSelected[:] = False
mpi.rootprint('Generating Features...')
for code in range(self.nCodes):
for metabin in range(self.nMetabins):
self.append_feature(code, metabin)
if tester is not None:
tester.append_feature(code, metabin)
mpi.rootprint('Feature generation took {} secs'.format(timer.lap()))
mpi.rootprint('Training...')
loss = self.retrain_model(None)
mpi.rootprint('Training took {} secs'.format(timer.lap()))
mpi.rootprint('Training accuracy: {}'.format(self.compute_current_accuracy()))
if tester is not None:
mpi.rootprint('Current Testing accuracy: {}'.format(tester.compute_test_accuracy(self.weights, self.b)))
示例12: detect
def detect(net, image_set, image_name, output_file):
"""Detect object classes in an image using pre-computed object proposals."""
# Load pre-computed Selected Search object proposals
#box_file = os.path.join(coco_root, 'boxes', image_set, image_name + '.mat')
box_file = os.path.join(coco_root, 'boxes_full', image_set, image_name + '.mat')
if not os.path.exists(box_file):
print 'File does not exist', box_file
return
obj_proposals = sio.loadmat(box_file)['boxes']
# Load the demo image
im_file = os.path.join(coco_root, 'images', image_set, image_name + '.jpg')
im = cv2.imread(im_file)
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im, obj_proposals)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
np.savez(output_file, scores=scores, boxes=boxes)
示例13: train_model
def train_model(self, max_iters):
#display = self.solver_param.display #40
#test_iter = 1
#test_interval = 1
#_accuracy = 0
#accuracy = 0
timer = Timer()
while self.solver.iter < max_iters:
#print self.solver.iter
#make one SGD update
timer.tic()
self.solver.step(1)
timer.toc()
"""
_train_loss += self.solver.net.blobs['euclidean_loss'].data
if (self.solver.iter-1) % display == 0:
train_loss[(self.solver.iter-1) // display] = _train_loss / display
_train_loss = 0
"""
if self.solver.iter % (self.solver_param.display) == 0:
print ('speed {:.3f}s / iter').format(timer.average_time)
"""
if self.solver.iter % test_interval == 0:
for test_it in range(test_iter):
self.solver.test_nets[0].forward()
_accuracy += self.solver.test_nets[0].blobs['loss3/top-5'].data
accuracy = _accuracy / test_iter
f.write(str(self.solver.iter) + ' ' + str(accuracy) + '\n')
_accuracy = 0
"""
"""
示例14: detect_bboxes
def detect_bboxes(net, im_names, subset_classes):
"""Detect object classes in an image using pre-computed object proposals."""
df = cnn_utils.create_bbox_data_frame(with_object_index=False)
for im_name in im_names:
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Demo for {}'.format(im_name)
# Load the input image.
im_file = os.path.join(FLAGS.data_dir, 'images', im_name)
im = cv2.imread(im_file)
im_size_x = im.shape[1]
im_size_y = im.shape[0]
# Detect all object classes and regress object bounds.
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(
timer.total_time, boxes.shape[0])
# Detect for each class
for subset_cls_ind in range(len(class_names_to_be_detected)):
cls = class_names_to_be_detected[subset_cls_ind]
try:
cls_ind = CLASSES.index(cls)
except:
print('error: class does not exist in training data: '
'{0}'.format(cls))
exit(-1)
cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
cls_scores = scores[:, cls_ind]
dets = np.hstack((cls_boxes,
cls_scores[:, np.newaxis])).astype(np.float32)
keep = nms(dets, FLAGS.nms_thresh)
dets = dets[keep, :]
inds = np.where(dets[:, -1] >= FLAGS.conf_thresh)[0]
if len(inds) > 0:
print ('{} {}(s) are detected.'.format(len(inds), cls))
for i in inds:
# ['image_name', 'class_index', 'x1', 'y1', 'x2', 'y2', 'score']
x1 = dets[i, 0]
y1 = dets[i, 1]
x2 = dets[i, 2]
y2 = dets[i, 3]
score = dets[i, -1]
if FLAGS.ignore_bbox_on_boundary:
# Ignore bounding boxes on the frame boundary.
if x1 <= 0 or x2 >= (im_size_x - 1) or \
y1 <= 0 or y2 >= (im_size_y - 1):
continue
# Append a row.
df.loc[len(df)] = [
im_name, subset_cls_ind, x1, y1, x2, y2, score]
return df
示例15: imdb_proposals
def imdb_proposals(net, imdb):
"""Generate RPN proposals on all images in an imdb."""
_t = Timer()
imdb_boxes = [[] for _ in xrange(imdb.num_images)]
for i in xrange(imdb.num_images):
im = None
if cfg.TRAIN.FORMAT == 'pickle':
with open(imdb.image_path_at(i), 'rb') as f:
im = cPickle.load(f)
else:
im = cv2.imread(imdb.image_path_at(i))
_t.tic()
imdb_boxes[i], scores = im_proposals(net, im)
_t.toc()
print 'im_proposals: {:d}/{:d} {:.3f}s' \
.format(i + 1, imdb.num_images, _t.average_time)
if 0:
dets = np.hstack((imdb_boxes[i], scores))
# from IPython import embed; embed()
_vis_proposals(im, dets[:3, :], thresh=0.9)
plt.show()
return imdb_boxes