本文整理汇总了Python中lib.utils.timer.Timer方法的典型用法代码示例。如果您正苦于以下问题:Python timer.Timer方法的具体用法?Python timer.Timer怎么用?Python timer.Timer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lib.utils.timer
的用法示例。
在下文中一共展示了timer.Timer方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: demo
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def demo(sess, net, image_name):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image
im = cv2.imread(image_name)
# 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)
示例2: demo
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def demo(sess, net, image_name):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image
im = cv2.imread(image_name)
# 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)
示例3: demo
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
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.FLAGS2["data_dir"], 'demo', 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
CONF_THRESH = 0.1
NMS_THRESH = 0.1
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)
示例4: ctpn
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def ctpn(img):
timer = Timer()
timer.tic()
img, scale = resize_im(img, scale=TextLineCfg.SCALE, max_scale=TextLineCfg.MAX_SCALE)
scores, boxes = test_ctpn(sess, net, img)
textdetector = TextDetector()
boxes = textdetector.detect(boxes, scores[:, np.newaxis], img.shape[:2])
timer.toc()
print("\n----------------------------------------------")
print(('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0]))
return scores, boxes, img, scale
示例5: ctpn
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def ctpn(sess, net, image_name):
timer = Timer()
timer.tic()
img = cv2.imread(image_name)
img, scale = resize_im(img, scale=TextLineCfg.SCALE, max_scale=TextLineCfg.MAX_SCALE)
scores, boxes = test_ctpn(sess, net, img)
textdetector = TextDetector()
boxes = textdetector.detect(boxes, scores[:, np.newaxis], img.shape[:2])
draw_boxes(img, image_name, boxes, scale)
timer.toc()
print(('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0]))
示例6: boxdetect
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def boxdetect(sess, net,im_file,output_path):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the image
im_file = im_file.replace('\\', '/')
im = cv2.imread(im_file)
image_name = im_file.split(r'/')[-1]
# 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
CONF_THRESH = 0.1
NMS_THRESH = 0.1
geetcode_bbox=[]
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, :]
bbox = vis_detections(im, cls, dets,image_name,output_path, thresh=CONF_THRESH)
geetcode_bbox.append(bbox)
return geetcode_bbox
示例7: train_epoch
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def train_epoch(self, model, data_loader, optimizer, criterion, writer, epoch, use_gpu):
model.train()
epoch_size = len(data_loader)
batch_iterator = iter(data_loader)
loc_loss = 0
conf_loss = 0
_t = Timer()
for iteration in iter(range((epoch_size))):
images, targets = next(batch_iterator)
if use_gpu:
images = Variable(images.cuda())
targets = [Variable(anno.cuda(), volatile=True) for anno in targets]
else:
images = Variable(images)
targets = [Variable(anno, volatile=True) for anno in targets]
_t.tic()
# forward
out = model(images, phase='train')
# backprop
optimizer.zero_grad()
loss_l, loss_c = criterion(out, targets)
# some bugs in coco train2017. maybe the annonation bug.
if loss_l.data[0] == float("Inf"):
continue
loss = loss_l + loss_c
loss.backward()
optimizer.step()
time = _t.toc()
loc_loss += loss_l.data[0]
conf_loss += loss_c.data[0]
# log per iter
log = '\r==>Train: || {iters:d}/{epoch_size:d} in {time:.3f}s [{prograss}] || loc_loss: {loc_loss:.4f} cls_loss: {cls_loss:.4f}\r'.format(
prograss='#'*int(round(10*iteration/epoch_size)) + '-'*int(round(10*(1-iteration/epoch_size))), iters=iteration, epoch_size=epoch_size,
time=time, loc_loss=loss_l.data[0], cls_loss=loss_c.data[0])
sys.stdout.write(log)
sys.stdout.flush()
# log per epoch
sys.stdout.write('\r')
sys.stdout.flush()
lr = optimizer.param_groups[0]['lr']
log = '\r==>Train: || Total_time: {time:.3f}s || loc_loss: {loc_loss:.4f} conf_loss: {conf_loss:.4f} || lr: {lr:.6f}\n'.format(lr=lr,
time=_t.total_time, loc_loss=loc_loss/epoch_size, conf_loss=conf_loss/epoch_size)
sys.stdout.write(log)
sys.stdout.flush()
# log for tensorboard
writer.add_scalar('Train/loc_loss', loc_loss/epoch_size, epoch)
writer.add_scalar('Train/conf_loss', conf_loss/epoch_size, epoch)
writer.add_scalar('Train/lr', lr, epoch)
示例8: test_epoch
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def test_epoch(self, model, data_loader, detector, output_dir, use_gpu):
model.eval()
dataset = data_loader.dataset
num_images = len(dataset)
num_classes = detector.num_classes
all_boxes = [[[] for _ in range(num_images)] for _ in range(num_classes)]
empty_array = np.transpose(np.array([[],[],[],[],[]]),(1,0))
_t = Timer()
for i in iter(range((num_images))):
img = dataset.pull_image(i)
scale = [img.shape[1], img.shape[0], img.shape[1], img.shape[0]]
if use_gpu:
images = Variable(dataset.preproc(img)[0].unsqueeze(0).cuda(), volatile=True)
else:
images = Variable(dataset.preproc(img)[0].unsqueeze(0), volatile=True)
_t.tic()
# forward
out = model(images, phase='eval')
# detect
detections = detector.forward(out)
time = _t.toc()
# TODO: make it smart:
for j in range(1, num_classes):
cls_dets = list()
for det in detections[0][j]:
if det[0] > 0:
d = det.cpu().numpy()
score, box = d[0], d[1:]
box *= scale
box = np.append(box, score)
cls_dets.append(box)
if len(cls_dets) == 0:
cls_dets = empty_array
all_boxes[j][i] = np.array(cls_dets)
# log per iter
log = '\r==>Test: || {iters:d}/{epoch_size:d} in {time:.3f}s [{prograss}]\r'.format(
prograss='#'*int(round(10*i/num_images)) + '-'*int(round(10*(1-i/num_images))), iters=i, epoch_size=num_images,
time=time)
sys.stdout.write(log)
sys.stdout.flush()
# write result to pkl
with open(os.path.join(output_dir, 'detections.pkl'), 'wb') as f:
pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)
# currently the COCO dataset do not return the mean ap or ap 0.5:0.95 values
print('Evaluating detections')
data_loader.dataset.evaluate_detections(all_boxes, output_dir)
示例9: predict
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def predict(self, img, threshold=0.6, check_time=False):
# make sure the input channel is 3
assert img.shape[2] == 3
scale = torch.Tensor([img.shape[1::-1], img.shape[1::-1]])
_t = {'preprocess': Timer(), 'net_forward': Timer(), 'detect': Timer(), 'output': Timer()}
# preprocess image
_t['preprocess'].tic()
x = Variable(self.preprocessor(img)[0].unsqueeze(0),volatile=True)
if self.use_gpu:
x = x.cuda()
if self.half:
x = x.half()
preprocess_time = _t['preprocess'].toc()
# forward
_t['net_forward'].tic()
out = self.model(x) # forward pass
net_forward_time = _t['net_forward'].toc()
# detect
_t['detect'].tic()
detections = self.detector.forward(out)
detect_time = _t['detect'].toc()
# output
_t['output'].tic()
labels, scores, coords = [list() for _ in range(3)]
# for batch in range(detections.size(0)):
# print('Batch:', batch)
batch=0
for classes in range(detections.size(1)):
num = 0
while detections[batch,classes,num,0] >= threshold:
scores.append(detections[batch,classes,num,0])
labels.append(classes-1)
coords.append(detections[batch,classes,num,1:]*scale)
num+=1
output_time = _t['output'].toc()
total_time = preprocess_time + net_forward_time + detect_time + output_time
if check_time is True:
return labels, scores, coords, (total_time, preprocess_time, net_forward_time, detect_time, output_time)
# total_time = preprocess_time + net_forward_time + detect_time + output_time
# print('total time: {} \n preprocess: {} \n net_forward: {} \n detect: {} \n output: {}'.format(
# total_time, preprocess_time, net_forward_time, detect_time, output_time
# ))
return labels, scores, coords
示例10: test_net
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def test_net(sess, net, imdb, weights_filename, max_per_image=100, thresh=0.05):
np.random.seed(cfg.FLAGS.rng_seed)
"""Test a Fast R-CNN network on an image database."""
num_images = len(imdb.image_index)
# all detections are collected into:
# all_boxes[cls][image] = N x 5 array of detections in
# (x1, y1, x2, y2, score)
all_boxes = [[[] for _ in range(num_images)]
for _ in range(imdb.num_classes)]
output_dir = get_output_dir(imdb, weights_filename)
# timers
_t = {'im_detect': Timer(), 'misc': Timer()}
for i in range(num_images):
im = cv2.imread(imdb.image_path_at(i))
_t['im_detect'].tic()
scores, boxes = im_detect(sess, net, im)
_t['im_detect'].toc()
_t['misc'].tic()
# skip j = 0, because it's the background class
for j in range(1, imdb.num_classes):
inds = np.where(scores[:, j] > thresh)[0]
cls_scores = scores[inds, j]
cls_boxes = boxes[inds, j * 4:(j + 1) * 4]
cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \
.astype(np.float32, copy=False)
keep = nms(cls_dets, 0.3)
cls_dets = cls_dets[keep, :]
all_boxes[j][i] = cls_dets
# Limit to max_per_image detections *over all classes*
if max_per_image > 0:
image_scores = np.hstack([all_boxes[j][i][:, -1]
for j in range(1, imdb.num_classes)])
if len(image_scores) > max_per_image:
image_thresh = np.sort(image_scores)[-max_per_image]
for j in range(1, imdb.num_classes):
keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0]
all_boxes[j][i] = all_boxes[j][i][keep, :]
_t['misc'].toc()
print('im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \
.format(i + 1, num_images, _t['im_detect'].average_time,
_t['misc'].average_time))
det_file = os.path.join(output_dir, 'detections.pkl')
with open(det_file, 'wb') as f:
pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)
print('Evaluating detections')
imdb.evaluate_detections(all_boxes, output_dir)
示例11: test_model
# 需要导入模块: from lib.utils import timer [as 别名]
# 或者: from lib.utils.timer import Timer [as 别名]
def test_model(self, resume_iter, max_per_image=100, thresh=0.):
self.prepare_construct(resume_iter)
"""Test a Fast R-CNN network on an image database."""
num_images = len(self.imdb.image_index)
# all detections are collected into:
# all_boxes[cls][image] = N x 5 array of detections in
# (x1, y1, x2, y2, score)
all_boxes = [[[] for _ in range(num_images)]
for _ in range(self.imdb.num_classes)]
output_dir = os.path.join(self.output_dir, 'fasterRcnn_iter_{}'.format(resume_iter))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# timers
_t = {'im_detect': Timer(), 'misc': Timer()}
for i in range(num_images):
im = cv2.imread(self.imdb.image_path_at(i))
_t['im_detect'].tic()
scores, boxes = im_detect(self.net, im)
_t['im_detect'].toc()
_t['misc'].tic()
# skip j = 0, because it's the background class
for j in range(1, self.imdb.num_classes):
inds = np.where(scores[:, j] > thresh)[0]
cls_scores = scores[inds, j]
cls_boxes = boxes[inds, j * 4:(j + 1) * 4]
cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \
.astype(np.float32, copy=False)
keep = nms(cls_dets, cfg.TEST.NMS) if cls_dets.size > 0 else []
cls_dets = cls_dets[keep, :]
all_boxes[j][i] = cls_dets
# Limit to max_per_image detections *over all classes*
if max_per_image > 0:
image_scores = np.hstack([all_boxes[j][i][:, -1]
for j in range(1, self.imdb.num_classes)])
if len(image_scores) > max_per_image:
image_thresh = np.sort(image_scores)[-max_per_image]
for j in range(1, self.imdb.num_classes):
keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0]
all_boxes[j][i] = all_boxes[j][i][keep, :]
_t['misc'].toc()
print('im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \
.format(i + 1, num_images, _t['im_detect'].toc(average=False),
_t['misc'].toc(average=False)))
det_file = os.path.join(output_dir, 'detections.pkl')
with open(det_file, 'wb') as f:
pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)
print('Evaluating detections')
self.imdb.evaluate_detections(all_boxes, output_dir)